Okay I'm going ahead and posting it as an answer. One way is to create the class that will holds the patterns.
public class Test {
public static void main(String[] args){
MyFormatter format = new MyFormatter("dd.MM.yyyy", "M/dd/yyyy");
LocalDate date = format.parse("3/30/2014"); //2014-03-30
LocalDate date2 = format.parse("30.03.2014"); //2014-03-30
}
}
class MyFormatter {
private final String[] patterns;
public MyFormatter(String... patterns){
this.patterns = patterns;
}
public LocalDate parse(String text){
for(int i = 0; i < patterns.length; i++){
try{
return LocalDate.parse(text, DateTimeFormatter.ofPattern(patterns[i]));
}catch(DateTimeParseException excep){}
}
throw new IllegalArgumentException("Not able to parse the date for all patterns given");
}
}
You could improve this as @MenoHochschild did by directly creating an array of DateTimeFormatter
from the array of String
you pass in the constructor.
Another way would be to use a DateTimeFormatterBuilder
, appending the formats you want. There may exists some other ways to do it, I didn't go deeply through the documentation :-)
DateTimeFormatter dfs = new DateTimeFormatterBuilder()
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
.appendOptional(DateTimeFormatter.ofPattern("dd.MM.yyyy"))
.toFormatter();
LocalDate d = LocalDate.parse("2014-05-14", dfs); //2014-05-14
LocalDate d2 = LocalDate.parse("14.05.2014", dfs); //2014-05-14