【发布时间】:2016-08-08 07:27:11
【问题描述】:
如果无法解析简单的DateTime,为什么可以将LocalDateTime 对象传递给ZonedDateTime.from() 方法,如下所示?
@Test
public void test() throws Exception {
GregorianCalendar.from(ZonedDateTime.from(LocalDateTime.parse("2016-08-31T23:00:59")));
}
结果:
java.time.DateTimeException: Unable to obtain ZonedDateTime from TemporalAccessor: 2016-08-31T23:00:59 of type java.time.LocalDateTime
at java.time.ZonedDateTime.from(ZonedDateTime.java:565)
【问题讨论】:
-
您是在问如何转换为
GregorianCalendar,还是在问为什么它允许您传递TemporalAccessor接口的实现并且只在运行时抱怨它? -
GeorgianCalendar 需要一个时区,所以实际上您可以通过
GregorianCalendar.from(ZonedDateTime.parse("2016-08-31T23:00:59+00:00"));提供一个时区。ZonedDateTime.from可能会因不同类型的输入以及 javadoc 中提到的输入而失败。 -
显示从旧日期时间类到 my Answer 中的 java.time 到 Convert java.util.Date to what “java.time” type? 的转换的图表可能很有用。还可以找到双向转换的示例代码。
-
@BasilBourque 这图真的很棒!