javadatetimeformatteroffsetdatetime

How to parse DateTime in format yyyyMMddHHmmss to OffsetDateTime using DateFormatter


I have an API for JSON parsing which requires a DateTimeFormatter instance in order to parse date time strings to OffsetDateTime. However I always get an exception Unable to obtain ZoneOffset from TemporalAccessor: {},ISO resolved to 2021-08-17T13:26:49 of type java.time.format.Parsed The API uses OffsetDateTime.parse(String, DateFormatter).

// DateTimeFormatter instance to be provided to the API
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
// this is how the API uses the DateTimeFormatter instance
OffsetDateTime dateTime = OffsetDateTime.parse("20210817132649", formatter);

How do I have to create the DateTimeFormatter in order to deliver a ZoneOffset, so that the API is able to parse the DateTime correctly. The ZoneOffset may be UTC.


Solution

  • Well, the string you passed in does not contain zone information, while an OffsetDateTime requires zone information.

    So you'll have to set a value for it.

    You could use the DateTimeFormatterBuilder class, which then can be instructed to use some default value if a field is missing from the parsed information:

    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .parseDefaulting(ChronoField.OFFSET_SECONDS, 0)
        .appendPattern("yyyyMMddHHmmss")
        .toFormatter(Locale.ROOT);
    

    You could also directly set an implied zone to the DateTimeFormatter:

    DateTimeFormatter.ofPattern("yyyyMMddHHmmss").withZone(ZoneOffset.UTC);