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

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

    Iterating over @Tunaki's solution, using streams, when the code need to accept different patterns in a configurable way :

    DateTimeFormatter dateTimeFormatter = dateFormats.stream()
            .map(DateTimeFormatter::ofPattern)
            .reduce(new DateTimeFormatterBuilder(), 
                    DateTimeFormatterBuilder::appendOptional, 
                    (f1, f2) -> f1.append(f2.toFormatter()))
            .toFormatter();
    

    In this case I don't care about the combiner part of the reducer, but I need it in the signature so I made the combiner correct.

    This code would virtually equivalent to if the above patterns (yyyy/MM/dd HH:mm:ss.SSSSSS, yyyy-MM-dd HH:mm:ss[.SSS], ddMMMyyyy:HH:mm:ss.SSS[ Z]) would be fed to the stream :

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

提交回复
热议问题