如何在Java中以YYYY-MM-DD HH:MI:Sec.Millisecond格式获取当前时间?

806

下面的代码可以获取当前时间,但没有提供毫秒级的信息。

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:SS2009-09-22 16:47:08)。

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

SimpleTextFormat将有效,它的最低时间单位是秒,但是如何获取毫秒?


37
当其他方法都失败时,阅读文档 - Hot Licks
6
FYI,像java.util.Datejava.util.Calendarjava.text.SimpleTextFormat这样的麻烦的旧日期时间类现在已经过时了,被java.time类替换。请参阅Oracle的教程 - Basil Bourque
16个回答

2

java.time

这个问题和被接受的回答使用了java.util.DateSimpleDateFormat,这是2009年的正确做法。 2014年3月,java.util日期时间API及其格式化API SimpleDateFormat现代日期时间API所取代。自那时起,强烈建议停止使用遗留的日期时间API。

使用现代日期时间API java.time 的解决方案:

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

关于此解决方案的一些重要注意事项:

  1. ZoneId.systemDefault() 替换为适用的 ZoneId,例如 ZoneId.of("America/New_York")
  2. 如果需要在系统的默认时区 (ZoneId) 中使用当前日期时间,则不需要使用 LocalDateTime#now(ZoneId zone);而是可以使用 LocalDateTime#now()
  3. 你可以在这里使用 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);
    }
}

以下是在我的系��时区 Europe/London 运行示例的输出:

2023-01-02 09:53:14.353

在线演示

Date Time Trail了解更多关于现代日期时间API的知识。


1

java.text(在Java 8之前)

public static ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>() {
    protected DateFormat initialValue() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    };
};

...
dateFormat.get().format(new Date());

java.time

public static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

...
dateTimeFormatter.format(LocalDateTime.now());

1

1

Ans:

DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
ZonedDateTime start = Instant.now().atZone(ZoneId.systemDefault());
String startTimestamp = start.format(dateFormatter);

0
Java 8中的文档将其命名为分之一秒, 而Java 6中的名称为毫秒。这让我感到困惑。

-1

您可以轻松地以您想要的格式获取它。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接