簡體   English   中英

將字符串解析為本地日期不會使用所需的世紀

[英]Parsing string to local date doesn't use desired century

我正在使用這個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}

你知道我為什么得到2090而不是1990年?

謝謝你的幫助

由於這個問題實際上是關於新的java.time而不是SimpleDateFormat我將引用以下相關部分

年份:字母數決定了使用填充的最小字段寬度。 如果字母數是2,則使用減少的兩位數形式。 對於打印,這將輸出最右邊的兩位數字。 對於解析,這將使用2000的基值進行解析,從而產生2000到2099(包括2000和2099)范圍內的一年。

我們看到Java-8 默認使用2000-2099的范圍,而不是像SimpleDateFormat的范圍 - 相對於今天的20年直到+ 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而不是y或相應的字段IsoFields.WEEK_BASED_YEAR 關於您沒有任何其他與周相關的字段的事實,我會假設正常的日歷年,而不是基於周的日歷年。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM