How to get the current time in YYYY-MM-DD HH:MI:Se

2019-01-01 06:23发布

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?

标签: java date
11条回答
倾城一夜雪
2楼-- · 2019-01-01 06:36
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
查看更多
牵手、夕阳
3楼-- · 2019-01-01 06:42

To complement the above answers, here is a small working example of a program that prints the current time and date, including milliseconds.

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

public class test {
    public static void main(String argv[]){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        Date now = new Date();
        String strDate = sdf.format(now);
        System.out.println(strDate);
    }
}

查看更多
旧人旧事旧时光
4楼-- · 2019-01-01 06:43

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.

查看更多
人间绝色
5楼-- · 2019-01-01 06:46

I would use something like this:

String.format("%tF %<tT.%<tL", dateTime);

Variable dateTime could be any date and/or time value, see JavaDoc for Formatter.

查看更多
浅入江南
6楼-- · 2019-01-01 06:48

try this:-

http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
Date date = new Date();
System.out.println(dateFormat.format(date));

or

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
查看更多
冷夜・残月
7楼-- · 2019-01-01 06:50

The doc in Java 8 names it fraction-of-second , while in Java 6 was named millisecond. This brought me to confusion

查看更多
登录 后发表回答