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
格式化失敗的行爲是一個錯誤還是一個功能?
我會提交一個錯誤報告,但我想確保我誤解了一些東西。