【发布时间】:2017-09-16 00:53:11
【问题描述】:
tl;博士
这失败了。
OffsetDateTime.now()
.format(
DateTimeFormatter.ofLocalizedDateTime( FormatStyle.LONG )
) // throws DateTimeException.
但ZonedDateTime 中具有相同偏移量的同一时刻有效。
为什么?
详情
当让java.time 通过DateTimeFormatter.ofLocalizedDateTime 自动本地化OffsetDateTime 的字符串表示形式时,如果格式化程序带有FormatStyle 或SHORT 或MEDIUM,则调用format 有效。但是当格式化程序带有LONG 或FULL 时,会抛出DateTimeException。然而ZonedDateTime 使用相同的时刻与相同的offset 成功。为什么?
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.LONG ) ;
OffsetDateTime odt = OffsetDateTime.now( ZoneId.systemDefault() ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( odt.getOffset() ) ; // Generate a `ZonedDateTime` with same moment and same offset as the `OffsetDateTime`.
// Succeeds.
String outputZdt = zdt.format( f ) ;
System.out.println( "outputZdt: " + outputZdt ) ;
// Fails. Throws exception.
if ( false ) {
String outputOdt = odt.format( f ) ; // Throws exception.
System.out.println( "outputOdt: " + outputOdt ) ;
}
看到这个code run live at IdeOne.com。
运行时……
好东西。
outputZdt:2017 年 9 月 16 日上午 8:42:14 Z
坏的。
Exception in thread "main" java.time.DateTimeException: Unable to extract value: class java.time.OffsetDateTime
at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:282)
at java.time.format.DateTimeFormatterBuilder$ZoneTextPrinterParser.format(DateTimeFormatterBuilder.java:3682)
at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2179)
at java.time.format.DateTimeFormatterBuilder$LocalizedPrinterParser.format(DateTimeFormatterBuilder.java:4347)
at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2179)
at java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1746)
at java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1720)
at java.time.OffsetDateTime.format(OffsetDateTime.java:1674)
at Ideone.main(Main.java:28)
我编写了该代码的核心来解决引发的异常odt.atZoneSameInstant( odt.getOffset() )。然后我意识到,为什么java.time 不在内部做同样的事情?为什么OffsetDateTime 不能格式化ZonedDateTime 具有相同的时刻和相同的偏移量成功?为什么我需要从OffsetDateTime 到ZonedDateTime 进行这种转换?
➟ OffsetDateTime 格式化失败的这种行为是错误还是功能?
我会提交一份错误报告,但我想确定我误解了什么。
【问题讨论】:
标签: java date-formatting java-time timezone-offset