I have an API that can return date values in JSON in three possible formats:
I am presenting two options, each with its pros and cons.
One, build a custom DateTimeFormatter
to accept your 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 one hand, it’s clean, on the other, someone could easily find it a bit tricky. For the three sample strings in your question it produces:
2017-04-30T00:00
2016-12-05T04:00
2016-12-05T00:00
The other option, try the three different formats in turn and pick the one that works:
public static LocalDateTime parse(String dateFromJson) {
try {
return LocalDateTime.parse(dateFromJson);
} catch (DateTimeParseException e) {
// ignore, try next format
}
try {
return LocalDateTime.parse(dateFromJson, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
} catch (DateTimeParseException e) {
// ignore, try next format
}
return LocalDate.parse(dateFromJson).atStartOfDay();
}
I don’t consider this the most beautiful code, still some may think it’s more straightforward than the first option? I think there’s a quality in relying on the built-in ISO formats alone. The results for your three sample strings are the same as above.