I present two options, each of which has its pros and cons.
One, create a custom DateTimeFormatterone to accept three possible formats:
public static LocalDateTime parse(String dateFromJson) {
DateTimeFormatter format = new DateTimeFormatterBuilder().append(DateTimeFormatter.ISO_LOCAL_DATE)
.optionalStart()
.appendLiteral('T')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.optionalStart()
.appendOffsetId()
.optionalEnd()
.optionalEnd()
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.toFormatter();
return LocalDateTime.parse(dateFromJson, format);
}
On the one hand, its clean, on the other hand, someone can easily find it a little harder. For the three lines of the example in your question, it produces:
2017-04-30T00:00
2016-12-05T04:00
2016-12-05T00:00
Alternatively, try three different formats in turn and select the one that works:
public static LocalDateTime parse(String dateFromJson) {
try {
return LocalDateTime.parse(dateFromJson);
} catch (DateTimeParseException e) {
}
try {
return LocalDateTime.parse(dateFromJson, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
} catch (DateTimeParseException e) {
}
return LocalDate.parse(dateFromJson).atStartOfDay();
}
I do not consider this the most beautiful code, but some may think that it is simpler than the first option? I think this is a quality based only on the built-in ISO formats. The results for the three test lines are the same as above.
source
share