如何以 2019101620000583 格式获取当前日期时间?

How to get current date time in the format 2019101620000583?

我是 Java 的新手。我正在尝试以长格式存储当前日期时间,例如 2019110820000583。

我试过使用 System.currentTimeMillis(),但它没有给出合并的日期和时间。它给了我 1573205716048.

这样的结果

java.time

获取 UTC 的当前时刻。

OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;

为您想要的输出定义格式模式。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuuMMddHHmmss" ) ;

生成包含所需格式文本的字符串。

String output = odt.format( f ) ;

对于时区,类似于上面的代码,但使用 ZonedDateTime 代替 OffsetDateTime

ZonedDateTime.now( ZoneId.of( "America/Montreal" ) ) 

ISO 8601

提示:将日期时间值序列化为文本时,通常最好使用标准 ISO 8601 格式。符合 ISO 8601 的“基本”版本:

  • 在日期部分和时间部分之间插入一个 T
  • 暂时在 UTC 中附加一个 Z。否则附加偏移量。

所以这个:

DateTimeFormatter.ofPattern( "uuuuMMdd'T'HHmmssXXXXX" )

查看完整示例 run live at IdeOne.com

OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuuMMdd'T'HHmmssXXXXX" ) ;
String output = odt.format( f ) ;

odt.toString(): 2019-11-09T04:38:47.972145Z

output: 20191109T043847Z


关于java.time

java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

要了解更多信息,请参阅 Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310

Joda-Time project, now in maintenance mode, advises migration to the java.time 类.

您可以直接与数据库交换 java.time 对象。使用 JDBC driver compliant with JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql.* 类.

在哪里获取java.time类?