2017-08-17 301 views
1

DateTimeFormatter模式"yyyy_'w'w"無法格式化它已解析的值。DateTimeFormatter可以解析,但不能格式化相同的輸入

val df = DateTimeFormatter.ofPattern("yyyy_'w'w") 
df: DateTimeFormatter = Value(YearOfEra,4,19,EXCEEDS_PAD)'_''w'Localized(WeekOfWeekBasedYear,1) 

val week = df.parse("2017_w19") 
week: temporal.TemporalAccessor = {Year=2017, WeekOfWeekBasedYear[WeekFields[SUNDAY,1]]=19},ISO 

df.format(week) 

的錯誤是:

java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: YearOfEra 
    java.time.format.Parsed.getLong(Parsed.java:203) 
    java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298) 
    java.time.format.DateTimeFormatterBuilder$NumberPrinterParser.format(DateTimeFormatterBuilder.java:2540) 
    java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2179) 
    java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1746) 
    java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1720) 

這是爲什麼?

+1

那是什麼語言? Scala呢? (並不是說這對您的問題確實很重要,對於Java工程師來說,這只是一個棘手的問題。)如果您沒有得到有用的答案,可以將它翻譯成Java以便覆蓋更廣泛的讀者。 –

回答

1

yyyy表示year-of-era field。但according to javadoc,也有uuuu的模式來代表year field(閱讀這些鏈接,看看他們之間的小差異 - 雖然目前的日期沒有太大的差異)。

的問題是:當你創建一個格式化與y,它採用了年的時代場,你可以通過值看:

值(YearOfEra,4, 19,EXCEEDS_PAD)

但是在解析時,得到的分析對象(在你的情況下,week變量)與年創建場 - 因爲你可以通過看值:

{ = 2017年一年,...


格式化設置與年的時代場。因此,當您嘗試格式化week時,它會嘗試從week變量中獲取此字段。由於此字段不存在(week僅包含,而不是年代),它會拋出UnsupportedTemporalTypeException

的解決方案是使用字段(u模式)在格式化:

val df = DateTimeFormatter.ofPattern("uuuu_'w'w") 
println(df) 
val week = df.parse("2017_w19") 
println(week) 
println(df.format(week)) 

輸出將是:

值(年,4,19 ,EXCEEDS_PAD)'_''w'Localized(WeekOfWeekBasedYear,1)
{ = 2017,WeekOfWeekBasedYear [WeekFields [SUNDAY,1] ] = 19},ISO
2017_w19

注意,現在的格式是用場創建,並format方法現在試圖從分析的對象得到這個領域,並不會引發任何異常。

+1

偉大的工作雨果!我很喜歡這個。 – Synesso

0

對於我來說,你不能使用DateTimeFormatter來格式化一個TemporalAccessor,它是一個過於寬泛的時間接口。嘗試先將它轉換爲DateTime對象。

相關問題