Parsing Json to zoned date time

Im reciving following json time format

"TimeEnd": "2017-05-24 09:52:51+02:00"

my dto is as follows:

 @JsonProperty("TimeEnd")
    @JsonDeserialize(using = JsonZonedDateTimeDeserializer.class)
    private ZonedDateTime timeEnd;

I wrote following deserializer

public class JsonZonedDateTimeDeserializer extends JsonDeserializer<ZonedDateTime> {


    @Override
    public ZonedDateTime deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
        return ZonedDateTime.parse(jp.getText());
    }
}

but im getting:

Text '2017-05-24 09:52:51+02:00' could not be parsed at index 10

I have tried multiple solutions but none of them seems to work...

Jon Skeet
people
quotationmark

You shouldn't be trying to parse it as a ZonedDateTime, as it really doesn't have a time zone - it has a UTC offset. OffsetDateTime is more appropriate here. It's worth differentiating between the two types - you can create a ZonedDateTime with a time zone that's just a fixed UTC offset, but you should understand that that's not the same as a "regular" time zone. If you only ever have offsets at a single instant, OffsetDateTime is better.

Now because your input value doesn't have the "T" required by the standard pattern, you'll need to use a custom pattern, but that's pretty easy:

import java.time.*;
import java.time.format.*;
import java.util.*;

public class Test {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
            "yyyy-MM-dd HH:mm:ssXXXXX", Locale.ROOT);
        String text = "2017-05-24 09:52:51+02:00";
        OffsetDateTime odt = OffsetDateTime.parse(text, formatter);
        System.out.println(odt);
    }       
}

people

See more on this question at Stackoverflow