Provide a flexible parser for LocalDate instances that can handle input in one of the following formats:
Here is the solution. You can define possible patterns inside appendPattern(). And to optional put defaults.
DateTimeFormatter parser = new DateTimeFormatterBuilder()
.appendPattern("[yyyy][yyyyMM][yyyyMMdd]")
.optionalStart()
.parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.optionalEnd()
.toFormatter();
System.out.println(parser.parse("2014",LocalDate::from)); // Works
System.out.println(parser.parse("201411",LocalDate::from)); // Works
System.out.println(parser.parse("20141102",LocalDate::from)); // Works
The output is
2014-01-01
2014-11-01
2014-11-02