下面的代码给出了当前时间。但是它并没有告诉我们毫秒。

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;
}

我有一个日期,格式是YYYY-MM-DD HH:MM:SS(2009-09-22 16:47:08)。

但是我想以YYYY-MM-DD HH:MM:SS的格式检索当前时间。MS(2009-09-22 16:47:08.128,其中128为毫秒)。

SimpleTextFormat可以很好地工作。这里最低的时间单位是秒,但我怎么也能得到毫秒呢?


当前回答

Java一行程序

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

JDK8风格

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

其他回答

这里有一个使用Millisecond......显示日期和时间的简单示例

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class MyClass{

    public static void main(String[]args){
        LocalDateTime myObj = LocalDateTime.now();
        DateTimeFormatter myFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
        String forDate = myObj.format(myFormat);
        System.out.println("The Date and Time are: " + forDate);
    }
}

Java 8中的文档将其命名为“秒的分数”,而在Java 6中则命名为“毫秒”。这使我感到困惑

你可以简单地得到你想要的格式。

String date = String.valueOf(android.text.format.DateFormat.format("dd-MM-yyyy", new java.util.Date()));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

试试这个:

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()));