javadatetimejava-8datetimeformatteroffsetdatetime

Why is this Date string failing the validation?


I have a JSON file with a value of 2020-03-07T04:11:20.000 for a field with given pattern yyyy-MM-dd'T'HH:mm:ss.SSS. I tried to add a Z at the end of it, but it keeps failing the validation. Any idea why?

I tried to do OffsetDateTime.parse(mytext, DateTimeFormatter.ofPattern(mypattern)) and it threw DateTimeParseException with Unable to obtain OffsetDateTime from TemporalAccessor


Solution

  • Since neither the pattern nor the input has a timezone offset, you can't parse it directly to OffsetDateTime. What you can do is parse the date as LocalDateTime and add the offset to the result.

    For example, using ZoneOffset.UTC:

    LocalDateTime ldt = LocalDateTime.parse(mytext, DateTimeFormatter.ofPattern(mypattern));
    OffsetDateTime odt = ldt.atOffset(ZoneOffset.UTC)