在Java中将带有毫秒的字符串转换为日期格式[复制]

参见英文答案 > Calendar date to yyyy-MM-dd format in java                                    9个
>            java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy                                    6个
>            How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?                                    11个
>            Change the format of Date Java [closed]                                    2个
我试图将一个毫秒(20180510-10:50:58.106)的字符串转换为java中的日期.但是,当我转换它时,我得到毫秒部分,但又在字符串中.我想要日期格式的相同部分.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class SimpleDateFormatExample {
public static void main(String[] args) {

    String curDate = "20180510-10:50:58.106";
    Date SysDateVar = null ;


    //SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd-HH:mm:ss.SSS");

    SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd-HH:mm:ss.SSS");
    //String Todate = format.format(curDate);
    //System.out.println("format.parse(curDate)="+Todate);
    String abc = null;

    try
    {

        abc = format.format(format.parse(curDate));

         System.out.println("SysDateVar ="+abc);

    SysDateVar = new Date ((long) (format.parse(curDate)).getTime());
    System.out.println("format.parse(curDate)="+ SysDateVar);
    }
    catch (ParseException e) {

        e.printStackTrace();
    }
}
}

输出是:

$javac SimpleDateFormatExample.java
$java -Xmx128M -Xms16M SimpleDateFormatExample

SysDateVar =20180510-10:50:58.106

format.parse(curDate)=Thu May 10 10:50:58 UTC 2018

变量abc是一个字符串.我想在Date变量中输出相同的输出.

解决方法:

当您在Date对象上调用System.out.println时,将默认调用此Date的toString()方法,它将以默认格式返回,如Thu May 10 10:50:58 UTC 2018.

您需要显式调用format.format(date)来获得所需的输出.

上一篇:计算几小时和几分钟的PHP


下一篇:Java日期解析具有微秒或纳秒精度