Scroll by week and week of week without separator

I am trying to parse week-week and week-week from a string without a separator character. For example. "201812" (week 12 of 2018). Like this:

DateTimeFormatter formatter = new DateTimeFormatterBuilder() .appendPattern("YYYYww") .parseDefaulting(WeekFields.ISO.dayOfWeek(), 1) .toFormatter(); LocalDate parse = LocalDate.parse("201803", formatter); 

But it gives me:

 java.time.format.DateTimeParseException: Text '201803' could not be parsed at index 0 

If I add a space between such fields:

 DateTimeFormatter formatter = new DateTimeFormatterBuilder() .appendPattern("YYYY ww") .parseDefaulting(WeekFields.ISO.dayOfWeek(), 1) .toFormatter(); LocalDate parse = LocalDate.parse("2018 03", formatter); 

It works great, with the result:

 2018-01-15 

Is this another mistake like this? Or am I missing something?

The workaround I found was to create custom formatting:

 DateTimeFormatter yearWeekPattern = new DateTimeFormatterBuilder().appendValue(IsoFields.WEEK_BASED_YEAR, 4) .appendValue(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 2) .parseDefaulting(WeekFields.ISO.dayOfWeek(), 1) .toFormatter(); LocalDate.parse("201803", yearWeekPattern).atStartOfDay(ZoneId.systemDefault()).toInstant(); 
+7
java localdate
source share
1 answer

This is a known bug that has been fixed for Java-9 .


If you are still in Java-8 and cannot upgrade to Java-9, then

  • you are either out of luck

  • or you can use a third-party library.

Joda-Time : (uses "x" for the weekly year)

 DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("xxxxww").toFormatter(); LocalDate joda = LocalDate.parse("201803", formatter); System.out.println(joda); // 2018-01-15 

Replacing parseDefaulting() not available.

Time4J ( my lib ):

 ChronoFormatter<CalendarWeek> f = ChronoFormatter.ofPattern( "YYYYww", PatternType.CLDR, Locale.ROOT, CalendarWeek.chronology() ); CalendarWeek cw = f.parse("201803"); java.time.LocalDate d = cw.at(Weekday.MONDAY).toTemporalAccessor(); System.out.println(d); // 2018-01-15 

Replacing parseDefaulting() can be achieved if you install the formatter not for the CalendarWeek type, but the base PlainDate type and use this common formatting method withDefault (...) . Example:

 ChronoFormatter<PlainDate> f = ChronoFormatter .ofDatePattern("YYYYww", PatternType.CLDR, Locale.ROOT) .withDefault(PlainDate.DAY_OF_WEEK, Weekday.MONDAY); PlainDate cw = f.parse("201803"); java.time.LocalDate d = cw.toTemporalAccessor(); 
+3
source share

All Articles