问题
How can we validate two formats "yyyy-MM-dd" and "yyyy-MM-dd'T'HH:mm:SSX" for a given string which can be of any of the two formats and either convert it to Instant or LocalDateTime?
LocalDateTime dateTime;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd[\'T\'HH:mm:SSX]");
TemporalAccessor temporalAccessor = formatter.parseBest(now, LocalDateTime::from, LocalDate::from);
if (temporalAccessor instanceof LocalDateTime) {
dateTime = (LocalDateTime)temporalAccessor;
} else {
dateTime = ((LocalDate)temporalAccessor).atStartOfDay();
}
When using the above format it's always resolving to LocalDate and chopping the time part.
回答1:
Changing the format to "yyyy-MM-dd[\'T\'HH:mm:ssX]" fixed it.
来源:https://stackoverflow.com/questions/62137376/is-there-a-way-to-parse-two-different-datetime-formats-into-localdatetime-or-ins