Parsing string for local date does not use the desired century

I use this DateTimeFormatter parameter:

DateTimeFormatter.ofPattern("ddMMYY") 

I want to 150790 line 150790 , and I got this error:

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

Obviously, I want to get the following TemporalAccessor :

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

Do you know why I got 2090 instead of 1990?

thanks for the help

+8
java date java-time 2-digit-year
source share
1 answer

Since this question is really about the new java.time package and NOT SimpleDateFormat , I will give the following relevant section :

Year: the number of letters determines the minimum width of the field below which is used to fill. If the number of letters is two, then the abbreviated form uses a two-digit form. For printing, it gives the rightmost two digits. For parsing, this will be parsed using a base value of 2000, resulting in a year ranging from 2000 to 2099 inclusive.

We see that Java-8 uses the 2000-2099 range by default , and not as the SimpleDateFormat range from -80 years to +20 years from today.

If you want to customize it, you should use appendValueReduced () . This is done inconveniently, but perhaps see here:

 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 

By the way, if you really need weekly years, then you need to use Y instead of y or the corresponding IsoFields.WEEK_BASED_YEAR field. Regarding the fact that you have no other fields related to the week, I would prefer a regular calendar year rather than a week.

+12
source share

All Articles