Converting a date time string, e.g. Joda DateTime (String) with Java 8

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 to java.time.LocalTimeDate. Joda has a good constructor for an object DateTimethat accepts in all three formats as strings and converts them. DateTime dt = new DateTime(StringFromAPI);enough.

Is there a similar feature in Java 8 ( java.timepackage)? It seems I now need to re-set Stringin order to check the format, and then create a LocalDateTime, ZonedDateTime, or LocalDateand turn in the past 2 LocalDateTime. Seems a little bulky for me. Is there an easy way?

0
source share
1 answer

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) {
        // 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 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.

+3
source

Source: https://habr.com/ru/post/1678323/


All Articles