2015-04-07 35 views
8

我使用此DateTimeFormatter:解析字符串本地日期不使用所需世紀

DateTimeFormatter.ofPattern("ddMMYY") 

我想解析字符串150790,我得到這個錯誤:

Unable to obtain LocalDate from TemporalAccessor: {DayOfMonth=15, MonthOfYear=7, WeekBasedYear[WeekFields[MONDAY,4]]=2090},ISO of type java.time.format.Parsed 

很顯然,我想獲得以下TemporalAccessor

{DayOfMonth=15, MonthOfYear=7, WeekBasedYear=1990} 

你知道我爲什麼得到了209年而不是1990年?

感謝您的幫助

回答

12

由於這個問題實際上是關於新java.time -package和NOT SimpleDateFormat我舉以下relevant section

Year: The count of letters determines the minimum field width below which padding is used. If the count of letters is two, then a reduced two digit form is used. For printing, this outputs the rightmost two digits. For parsing, this will parse using the base value of 2000, resulting in a year within the range 2000 to 2099 inclusive.

我們看到的Java-8使用範圍2000- 2099每默認,不像SimpleDateFormat範圍-80年,直到+20年相對於今天。

如果你想配置它,那麼你必須使用appendValueReduced()。這樣的設計是在不方便的方式,但可能的話,在這裏看到:

String s = "150790"; 

// old code with base range 2000-2099 
DateTimeFormatter dtf1 = 
    new DateTimeFormatterBuilder().appendPattern("ddMMyy").toFormatter(); 
System.out.println(dtf1.parse(s)); // 2090-07-15 

// improved code with base range 1935-2034 
DateTimeFormatter dtf2 = 
    new DateTimeFormatterBuilder().appendPattern("ddMM") 
    .appendValueReduced(
    ChronoField.YEAR, 2, 2, Year.now().getValue() - 80 
).toFormatter(); 
System.out.println(dtf2.parse(s)); // 1990-07-15 

順便說一句,如果你真的想根據本週年,那麼你必須使用的,而不是y或相應的字段IsoFields.WEEK_BASED_YEAR年。關於您沒有任何其他與周有關的字段,我會假定正常的日曆年,而不是以周爲單位的日曆年。