I want to parse some text into a date. However, there is no guarantee that the text has the desired format. It may be 2012-12-12
or 2012
or even .
Currently, I am down the path to nested try-catch blocks, but that's not a good direction (I suppose).
LocalDate parse;
try {
parse = LocalDate.parse(record, DateTimeFormatter.ofPattern("uuuu/MM/dd"));
} catch (DateTimeParseException e) {
try {
Year year = Year.parse(record);
parse = LocalDate.from(year.atDay(1));
} catch (DateTimeParseException e2) {
try {
// and so on
} catch (DateTimeParseException e3) {}
}
}
What's an elegant solution to this problem? Is it possible to use Optional
s which is absent in case a exception happened during evaluation? If yes, how?
This can be done in an elegant fashion using DateTimeFormatter
optional sections. An optional section is started by the [
token and is ended by the ]
token.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("[yyyy[-MM-dd]]");
System.out.println(formatter.parse("2012-12-12")); // prints "{},ISO resolved to 2012-12-12"
System.out.println(formatter.parse("2012")); // prints "{Year=2012},ISO"
System.out.println(formatter.parse("")); // prints "{},ISO"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With