tl;博士
Instant // Represent a moment in UTC with resolution of nanoseconds.
.ofEpochMilli( // Parsing a count of milliseconds.
1_567_697_400_000L // Count of whole seconds since first moment of 1970 in UTC.
) // Returns an `Instant` object.
.atZone( // Adjust from UTC to some time zone. Same moment, different wall-clock time.
ZoneId.of( "America/Los_Angeles" ) // Use proper time zone names in `Continent/Region` format rather than mere offset-from-UTC (hours-minutes-seconds).
) // Returns a `ZonedDateTime` object.
.toString() // Generate text in standard ISO 8601 format, wisely extended to append name of time zone in square brackets.
详情
另外两个答案by Aditi Gupta 和Ole V.V. 都是正确的。我将添加一些示例代码。
您在一年前使用的糟糕的日期时间类被 java.time 类所取代。
Instant
我正在尝试转换时间戳(毫秒)
如果您的毫秒数是自 UTC 1970 年第一刻的纪元参考以来,则解析为 Instant。
long input = 1_567_697_400_000L ; // Count of milliseconds since 1970-01-01T00:00:00Z.
Instant instant = Instant.ofEpochMilli( input ) ;
instant.toString(): 2019-09-05T15:30:00Z
时区
到另一个时区(GMT-7:00 美国/洛杉矶)
使用proper time zone name 而不是仅仅从 UTC 偏移。
将时区 (ZoneId) 应用到您的 Instant 以调整到时区,从而生成 ZonedDateTime 对象。
ZoneId z = ZoneId.of( "America/Los_Angeles" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
zdt.toString(): 2019-09-05T08:30-07:00[美国/洛杉矶]
始终指定时区
我的本地时区是“GMT+5:30”
您自己的本地时区应该与您的日期时间处理无关,JVM 的默认时间时间也应该如此。
在java.time 中,时区和偏移量参数是可选的。如果省略,则隐式应用 JVM 的当前默认时区。在我看来,这是 java.time 设计中为数不多的缺陷之一——这些区域参数应该是必需的。我建议您始终明确指定所需/预期的时区。
如果您愿意,我们可以调整到您自己的时区。 明确询问 JVM 的当前默认时区,以使您的代码意图对读者一目了然。
ZoneId zDefault = ZoneId.systemDefault() ;
ZonedDateTime zdtDefault = zdt.withZoneSameInstant( zDefault ) ;
zdtDefault.toString(): 2019-09-05T21:00+05:30[亚洲/加尔各答]
IdeOne.com 演示
看到这一切code run live at IdeOne.com。
关于java.time
java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.Date、Calendar 和 SimpleDateFormat。
要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310。
Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。
您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。
从哪里获得 java.time 类?
ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如Interval、YearWeek、YearQuarter 和more。