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

后端 未结 5 1055
我寻月下人不归
我寻月下人不归 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:03

    There is no direct facility to do this, but you can use optional sections. Optional sections are enclosed inside squared brackets []. This allows for the whole section of the String to parse to be missing.

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(""
        + "[yyyy/MM/dd HH:mm:ss.SSSSSS]"
        + "[yyyy-MM-dd HH:mm:ss[.SSS]]"
        + "[ddMMMyyyy:HH:mm:ss.SSS[ Z]]"
    );
    

    This formatter defines 3 grand optional sections for the three main patterns you have. Each of them is inside its own optional section.

    Working demo code:

    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(""
            + "[yyyy/MM/dd HH:mm:ss.SSSSSS]"
            + "[yyyy-MM-dd HH:mm:ss[.SSS]]"
            + "[ddMMMyyyy:HH:mm:ss.SSS[ Z]]"
        , Locale.ENGLISH);
        System.out.println(LocalDateTime.parse("2016/03/23 22:00:00.256145", formatter));
        System.out.println(LocalDateTime.parse("2016-03-23 22:00:00", formatter));
        System.out.println(LocalDateTime.parse("2016-03-23 22:00:00.123", formatter));
        System.out.println(LocalDateTime.parse("23Mar2016:22:00:00.123", formatter));
        System.out.println(LocalDateTime.parse("23Mar2016:22:00:00.123 -0800", formatter));
    }
    

提交回复
热议问题