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

前端 未结 1 738
隐瞒了意图╮
隐瞒了意图╮ 2020-12-07 05:50

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
<
相关标签:
1条回答
  • 2020-12-07 06:20

    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.

    0 讨论(0)
提交回复
热议问题