Convert date time string like Joda DateTime(String) with Java 8

柔情痞子 提交于 2019-12-17 21:37:06

问题


I have an API that can return date values in JSON in three possible formats:

  1. 2017-04-30T00:00+02:00
  2. 2016-12-05T04:00
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!