How to get the current time in YYYY

The code below gives me the current time. But it does not tell anything about milliseconds.

public static String getCurrentTimeStamp() {
    SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//dd/MM/yyyy
    Date now = new Date();
    String strDate = sdfDate.format(now);
    return strDate;
}

I get date in the format 2009-09-22 16:47:08 (YYYY-MM-DD HH:MI:Sec) .

But I want to retrieve the current time in the format 2009-09-22 16:47:08.128 ((YYYY-MM-DD HH:MI:Sec.Ms)- where 128 tells the millisecond.

SimpleTextFormat will work fine. Here the lowest unit of time is second, but how do I get millisecond as well?


SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

A Java one liner

public String getCurrentTimeStamp() {
    return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
}

in JDK8 style

public String getCurrentLocalDateTimeStamp() {
    return LocalDateTime.now()
       .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
}

You only have to add the millisecond field in your date format string:

new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

The API doc of SimpleDateFormat describes the format string in detail.

链接地址: http://www.djcxy.com/p/59496.html

上一篇: 如何在C ++中初始化一个向量

下一篇: 如何在YYYY中获得当前时间