2014-08-29 42 views
52

格式LocalDateTime我有這個簡單的代碼:與時區在Java8

DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z"); 
LocalDateTime.now().format(FORMATTER) 

然後,我會得到以下異常:

java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: OffsetSeconds 
at java.time.LocalDate.get0(LocalDate.java:680) 
at java.time.LocalDate.getLong(LocalDate.java:659) 
at java.time.LocalDateTime.getLong(LocalDateTime.java:720) 
at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298) 
at java.time.format.DateTimeFormatterBuilder$OffsetIdPrinterParser.format(DateTimeFormatterBuilder.java:3315) 
at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2182) 
at java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1745) 
at java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1719) 
at java.time.LocalDateTime.format(LocalDateTime.java:1746) 

如何解決這個問題?

+0

不確定,我想Z需要單引號。 – msknapp 2014-08-29 03:51:56

回答

88

LocalDateTime是沒有時區的日期時間。您指定格式中的時區偏移格式符號,但是,LocalDateTime不具有此類信息。這就是錯誤發生的原因。

如果你想要時區信息,你應該使用ZonedDateTime

DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z"); 
ZonedDateTime.now().format(FORMATTER) 
=> "20140829 14:12:22.122000 +09" 
+2

超級有用。不知道我會如此輕鬆地抓住時區片。很好的答案。謝謝! – 2016-02-26 01:03:49

29

的前綴,在JSR-310「本地」(又名java.time包中的Java-8)不表明存在這樣的類(這裏:LocalDateTime)的內部狀態的時區信息。儘管經常有誤導性的名稱,例如LocalDateTimeLocalTime等類別沒有時區信息或偏移量

您嘗試使用偏移量信息(由模式符號Z指示)來格式化這種時間類型(不包含任何偏移量)。所以格式化程序試圖訪問一個不可用的信息,並且必須拋出你觀察到的異常。

解決方案:

使用具有這樣的偏移或時區信息的類型。在JSR-310中,它可以是OffsetDateTime(包含偏移量,但不包含DST規則的時區)或ZonedDateTime。您可以通過查詢方法isSupported(TemporalField).注意所有支持的類型。 OffsetDateTimeZonedDateTime支持字段OffsetSeconds,但不支持LocalDateTime

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z"); 
String s = ZonedDateTime.now().format(formatter); 
+0

用什麼前綴替換前綴「Local」以避免混淆? – Matthew 2016-03-06 19:06:18

+0

@Mthethew還有一個[辯論](https://sourceforge.net/p/threeten/mailman/message/29960633/)由Bank Credit Suisse發起,建議名稱爲'PlainDateTime'等等。可能更好,因爲前綴「plain 「確實表明沒有什麼比僅僅日期時間更多。如果我們還在Java v1.0之前,那麼沒有前綴會更好,但是像Date這樣的名稱已經被舊的JDK保留了。 – 2016-03-06 20:05:45