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

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可以很好地工作。这里最低的时间单位是秒,但我怎么也能得到毫秒呢?


当前回答

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

String date = String.valueOf(android.text.format.DateFormat.format("dd-MM-yyyy", new java.util.Date()));

其他回答

我会用这样的方法:

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

变量dateTime可以是任何日期和/或时间值,参见JavaDoc中的Formatter。

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

使用此命令获取指定格式的当前时间:

 DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 System.out.print(dateFormat.format(System.currentTimeMillis()));  }

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

你只需要在日期格式字符串中添加毫秒字段:

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

SimpleDateFormat的API文档详细描述了格式字符串。