简而言之
Instant.ofEpochMilli( 1_322_018_752_992L ) // Parse count of milliseconds-since-start-of-1970-UTC into an `Instant`.
.atZone( ZoneId.of( "Africa/Tunis" ) ) // Assign a time zone to the `Instant` to produce a `ZonedDateTime` object.
细节
其他答案使用过时或不正确的类。
避免使用旧的日期时间类,例如java.util.Date/.Calendar。它们被证明设计不佳、令人困惑和麻烦。
java.time
The
java.time framework is integrated into Java 8 and later versions. Many of its features are
backported to Java 6 & 7 and
adapted to Android. It was developed by some of the same people who created
Joda-Time.
An
Instant
represents a specific moment on the timeline in
UTC with a precision of
nanoseconds. Its
epoch is the first moment of 1970 in UTC.
假设您的输入数据是从1970-01-01T00:00:00Z以毫秒为单位计数的(问题中不太清楚),那么我们可以轻松地实例化一个
Instant
。
Instant instant = Instant.ofEpochMilli( 1_322_018_752_992L );
instant.toString(): 2011-11-23T03:25:52.992Z
在标准的ISO 8601格式化字符串中,Z
代表Zulu
,表示UTC。
使用正确的时区名称来应用时区,以获取ZonedDateTime
。
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = instant.atZone( zoneId );
请查看这个在IdeOne.com上实时运行的代码。
Asia/Kolkata
时区?
我猜你的代码受到了印度时区的影响。我们可以看到,调整为Asia/Kolkata
时区后,报告的时间与您报告的相同,08:55
,比我们的UTC值03:25
快五个半小时。
2011-11-23T08:55:52.992+05:30[Asia/Kolkata]
默认时区
您可以应用JVM的当前默认时区。请注意,在运行时期间默认值可能会发生更改。JVM中任何应用程序的任何线程中的任何代码都可以更改当前默认设置。如果重要,请询问用户其所需/预期的时区。
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
关于 java.time
java.time 框架内置于 Java 8 及以上版本中。这些类取代了老旧的遗留日期时间类,如 java.util.Date
, Calendar
, 和 SimpleDateFormat
,使得日期和时间的处理更加简单易用。
Joda-Time项目现在处于维护模式,建议迁移到java.time类。
想要了解更多,请查看Oracle教程。在Stack Overflow上搜索许多示例和解释。规范为JSR 310。
使用符合JDBC 4.2或更高版本的JDBC驱动程序,您可以直接与数据库交换java.time对象,无需使用字符串或java.sql.*类。
如何获取java.time类?
这个
ThreeTen-Extra 项目扩展了 java.time 的额外类。该项目是 java.time 可能未来添加的试验场。您可能会在这里找到一些有用的类,例如
Interval
、
YearWeek
、
YearQuarter
和
更多。
GregorianCalendar
、SimpleDateFormat
等)和优秀的Joda-Time库现已被现代的java.time类取代。 - Basil Bourque