I currently have a Joda date parser that uses the DateTimeFormatterBuilder with half a dozen different date formats that I may receive.
I\'m migrating to Java 8\'s D
Based on answer from @Brice I wrote the following method, which worked best for me
private LocalDate parseDate(String date) {
DateTimeFormatter yearFormat = new DateTimeFormatterBuilder()
.appendPattern("yyyy")
.parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.toFormatter();
DateTimeFormatter yearAndMonthFormat = new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM")
.parseDefaulting(ChronoField.DAY_OF_MONTH,1)
.toFormatter();
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendOptional(DateTimeFormatter.ISO_DATE)
.appendOptional(yearAndMonthFormat)
.appendOptional(yearFormat)
.toFormatter();
LocalDate result = LocalDate.parse(date, formatter);
return result;
}
Pay attention to the order of optional formatters added to the last one. Reverse order would only work for dates of the type "yyyy". The proposed order allows me to parse all of the following:
Just adding for the case someone would have similar use case.