Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant solution to parse date

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 Optionals which is absent in case a exception happened during evaluation? If yes, how?

like image 647
helt Avatar asked Jan 08 '23 11:01

helt


1 Answers

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"
like image 103
Tunaki Avatar answered Jan 27 '23 19:01

Tunaki