tl;博士
LocalDateTime.parse( "2016-12-21T07:48:36" ) // Parse as a `LocalDateTime` given the lack of an offset or zone. *Not* an actual moment, only a rough approximation of potential moments along a range of about 26-27 hours.
.atOffset( ZoneOffset.ofHours( 14 ) ) // Assign an offset-from-UTC as context, giving meaning to determine an actual point on the timeline.
.toInstant() // Renders `Instant` object in UTC.
java.time
现代方法是使用 Java 8 及更高版本中内置的 java.time 类。 ThreeTen-Backport 项目中的大部分功能都向后移植到 Java 6 和 7。
ZoneOffset offset = ZoneOffset.ofHours( 14 ); // fourteen hours ahead of UTC.
将字符串解析为LocalDateTime,因为它缺少有关偏移量或区域的任何信息。您的输入采用标准ISO 8601 格式,因此无需指定格式模式。
LocalDateTime ldt = LocalDateTime.parse( "2016-12-21T07:48:36" );
将偏移量应用于本地日期时间以获取 OffsetDateTime 对象。
OffsetDateTime odt = ldt.atOffset( offset );
从中提取一个始终位于UTC 中的Instant。
Instant instant = odt.toInstant();
instant.toString(): 2016-12-20T17:48:36Z
在UTC 中,值是不同的日期,即 20 日而不是 21 日。
见live code at IdeOne.com。
关于java.time
java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.Date、Calendar 和 SimpleDateFormat。
Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。
要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310。
使用符合JDBC 4.2 或更高版本的JDBC driver,您可以直接与您的数据库交换java.time 对象。不需要字符串也不需要 java.sql.* 类。
从哪里获得 java.time 类?
ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如Interval、YearWeek、YearQuarter 和more。