I've got three types of ISO dates: yyyy
, yyyy-MM
, yyyy-MM-dd
. In other words, increasingly getting more precise from year to month to day. Should a field be absent, it should be mapped to the lowest possible value (missing day -> first day of the month // missing month -> first month of the year).
A day cannot ever be there without a month, so I thought it would work fine using nested brackets:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy[-MM[-dd]]");
LocalDate ld = LocalDate.parse("2019-08-10", dtf); // ok
ld = LocalDate.parse("2019-08", dtf); // error
ld = LocalDate.parse("2019", dtf); // error
But alas, the two bottom ones spit out a DateTimeParseException. Is this even possible?
EDIT: Got it. Turns out, as mentioned in the comments, defaults aren't set implicitly. This fixes it:
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ofPattern("yyyy[-MM[-dd]]"))
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
.toFormatter();