Parse String for Unknown TemporalAccessor

I get a query parameter with an unknown time (date, time or timestamp in ISO format) and I want to analyze it for java.time.temporal.TemporalAccessor:

  • LocalDatewhen a string represents a date of type "2018-02-28"
  • or LocalDateTimewhen the string represents a timestamp of type"2018-02-28T11:20:00"

The following attempt results in DateTimeParseException:

TemporalAccessor dt = DateTimeFormatter.ISO_DATE_TIME.parseBest(str, LocalDateTime::from, LocalDate::from);

The decision about the length of the string or the appearance of the “T” that is being used DateTimeFormatterseems a bit hacked to me. Just like trying one format after another.

The best decision?

+1
source share
1 answer

Your problem is that ISO_DATE_TIMEtime expects, as the name indicates. In your case, you need to use an optional section in your template.

:

DateTimeFormatter FMT = new DateTimeFormatterBuilder()
        .append(DateTimeFormatter.ISO_LOCAL_DATE)
        .optionalStart() //HERE WE INDICATE THAT THE TIME IS OPTIONAL
        .appendLiteral('T')
        .append(DateTimeFormatter.ISO_LOCAL_TIME)
        .toFormatter();

String input = "2018-02-28";
TemporalAccessor dt = FMT.parseBest(input, LocalDateTime::from, LocalDate::from);        
0

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


All Articles