tl; dr
失败。OffsetDateTime失败,使用本地化格式化程序使用FormatStyle的LONG或FULL
OffsetDateTime.now()
.format(
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)
) // throws DateTimeException.
但是在ZonedDateTime
工作中具有相同偏移量的同一时刻。
为什么?
详细
当让java.time
通过DateTimeFormatter.ofLocalizedDateTime
自动本地化OffsetDateTime
的字符串表示,呼吁format
作品,如果格式化携带SHORT
或MEDIUM
一个FormatStyle
。但是,如果格式化程序包含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分十四秒ž
坏。
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
格式化失败的行为是一个错误还是一个功能?
我会提交一个错误报告,但我想确保我误解了一些东西。