问题
I'm getting a request parameter with unknown temporal (date, time or timestamp in ISO format) and want to parse it into a java.time.temporal.TemporalAccessor
:
LocalDate
when the string represents a date like"2018-02-28"
- or
LocalDateTime
when the string represents a timestamp like"2018-02-28T11:20:00"
The following attempt results into DateTimeParseException
:
TemporalAccessor dt = DateTimeFormatter.ISO_DATE_TIME.parseBest(str, LocalDateTime::from, LocalDate::from);
Deciding on the length of the string or the occurrence of a "T", which DateTimeFormatter
to use, seems to me a little bit hacky. As well as trying one format after another.
Any better solution?
回答1:
Your problem is that ISO_DATE_TIME
expects a time, as the name indicates. In your case you need to use an optional section in your pattern.
This should work as required:
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);
来源:https://stackoverflow.com/questions/49026914/parse-string-for-unknown-temporalaccessor