Java 8 Date equivalent to Joda's DateTimeFormatterBuilder with multiple parser formats?

后端 未结 5 1022
我寻月下人不归
我寻月下人不归 2020-12-09 08:50

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

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-09 09:11

    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:

    • 2014
    • 2014-10
    • 2014-03-15

    Just adding for the case someone would have similar use case.

提交回复
热议问题