I'm trying to parse a week-based-year and week-of-week-based-year from a string without any separator character. E.g. "201812" (week 12 of year 2018). Like this:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("YYYYww")
.parseDefaulting(WeekFields.ISO.dayOfWeek(), 1)
.toFormatter();
LocalDate parse = LocalDate.parse("201803", formatter);
But this gives me:
java.time.format.DateTimeParseException: Text '201803' could not be parsed at index 0
If I add a space between the fields like so:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("YYYY ww")
.parseDefaulting(WeekFields.ISO.dayOfWeek(), 1)
.toFormatter();
LocalDate parse = LocalDate.parse("2018 03", formatter);
It works fine, with result:
2018-01-15
Is this another bug like this one? Or am I missing something?
The workaround I found was building a custom formatter:
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();
input.substring(0, 4) + "-" + input.substring(4)
but I have left it out of my answer because I assume that you look for a library-based solution. – Polygamy