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
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();