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

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 8中的文档将其命名为“秒的分数”,而在Java 6中则命名为“毫秒”。这使我感到困惑

其他回答

java.time

问题和接受的答案使用java.util.Date和SimpleDateFormat,这在2009年是正确的做法。2014年3月,java。SimpleDateFormat已经被现代日期时间API所取代。从那时起,强烈建议停止使用遗留的日期-时间API。

使用java解决方案。time,现代date-time API:

LocalDateTime.now(ZoneId.systemDefault())
             .format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS"))

关于这个解决方案的一些要点:

将ZoneId. systemdefault()替换为适用的ZoneId,例如ZoneId.of("America/New_York")。 如果当前日期-时间在系统的默认时区(ZoneId)中是必需的,则不需要使用LocalDateTime#now(ZoneId zone);相反,您可以使用LocalDateTime#now()。 你可以用y代替u,但我更喜欢u。

演示:

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

class Main {
    public static void main(String args[]) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
        // Replace ZoneId.systemDefault() with the applicable ZoneId e.g.
        // ZoneId.of("America/New_York")
        LocalDateTime ldt = LocalDateTime.now(ZoneId.systemDefault());
        String formattedDateTimeStr = ldt.format(formatter);
        System.out.println(formattedDateTimeStr);
    }
}

在我的系统时区欧洲/伦敦运行示例的输出:

2023-01-02 09:53:14.353

在线演示

从Trail: Date Time了解更多关于现代Date-Time API的信息。

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

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

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

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

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

这里有一个使用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);
    }
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");