如何使用 Java 在 UTC 中打印从纪元开始的毫秒计数作为日期时间?

How do I print a millisecond count from epoch as a date-time in UTC using Java?

我正在尝试使用 Java 将以毫秒为单位的时间格式化为 UTC 日期。我有以下代码:

long ms = 1427590800000;
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.ROOT);
cal.setTimeInMillis(ms);
Date date = cal.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd hh:mm:ss");
System.out.println(dateFormat.format(date)); // 2015-03-29 02:00:00

这是在 BST(即使用默认时区)而不是 UTC 中打印时间。日历上设置的时区似乎与打印日期无关。

UTC 的实际时间由以下 python 片段显示:

import datetime
ms = 1427590800000
print datetime.datetime.utcfromtimestamp(ms/1000.0) # 2015-03-29 01:00:00

将默认 JVM 时区设置为 "UTC" 会导致打印正确的日期,但这似乎不是一个安全的解决方案。

如果您想要一个所需的时区,您需要在格式化之前将 timezone 设置为格式化程序。

使用dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));然后调用dateFormat.format(date)

java.time

现代方法使用行业领先的 java.time 类.

解析为 Instant,UTC 中的一个时刻,分辨率为纳秒。

long input = 1_427_590_800_000L ;
Instant instant = Instant.ofEpochMilli( input ) ;

ISO 8601

生成标准 ISO 8601 格式的字符串。

String output = instant.toString() ;

2015-03-29T01:00:00Z



关于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类?

ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.