问题
I have an API that can return date values in JSON in three possible formats:
- 2017-04-30T00:00+02:00
- 2016-12-05T04:00
- 2016-12-05
I need to convert all three into a java.time.LocalTimeDate
. Joda has a nice constructor on the DateTime
object which takes in all three formats as Strings and converts them. DateTime dt = new DateTime(StringFromAPI);
is enough.
Is there a similar capability in Java 8 (java.time
package)? It seems I now first have to regex the String
to check the format, then create either a LocalDateTime
, ZonedDateTime
or LocalDate
and convert the latter 2. to LocalDateTime
. Seems a bit cumbersome to me. Is there a easy way?
回答1:
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.
来源:https://stackoverflow.com/questions/43208870/convert-date-time-string-like-joda-datetimestring-with-java-8