Elegant Parsing Solution

I want to parse text on a date. However, there is no guarantee that the text has the desired format. It can be 2012-12-12either 2012or or even .

I'm currently on the way to nested try-catch blocks, but this is 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 is an elegant solution to this problem? Is it possible to use Optionalthat is absent in case of exception during the assessment? If so, how?

+4
source share
2 answers

The class DateTimeFormatterBuildercontains building blocks for this work:

LocalDate now = LocalDate.now();
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
    .appendPattern("[uuuu[-MM[-dd]]]")
    .parseDefaulting(ChronoField.YEAR, now.getYear())
    .parseDefaulting(ChronoField.MONTH_OF_YEAR, now.getMonthValue())
    .parseDefaulting(ChronoField.DAY_OF_MONTH, now.getDayOfMonth())
    .toFormatter();
System.out.println(LocalDate.parse("2015-06-30", fmt));
System.out.println(LocalDate.parse("2015-06", fmt));
System.out.println(LocalDate.parse("2015", fmt));
System.out.println(LocalDate.parse("", fmt));

parseDefaulting() . a LocalDate , .

"[...]" , , .

+4

, DateTimeFormatter . [ ].

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"
+5

Source: https://habr.com/ru/post/1609590/


All Articles