Jatin Bodarya
Jatin Bodarya

Reputation: 1455

Deserializing java date into Instant

I need to deserialize below two foramt into java.time.Instant in a singe code

2020-04-23T10:51:24.238+01:00 and 2019-11-11T15:44:10.201Z

I'm getting belwow error in first case

nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type java.time.Instant from String "2020-04-23T10:51:24.238+01:00": com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type java.time.Instant from String "2020-04-23T10:51:24.238+01:00": Failed to deserialize java.time.Instant: (java.time.format.DateTimeParseException) Text '2020-04-23T10:51:24.238+01:00' could not be parsed at index 23

Is there any solution ? Also Is there any way to deserialize java.util.Date into java.time.Instant Note : Its an API response and I can't use Date in deserialized class i.e consumer

Upvotes: 0

Views: 2127

Answers (2)

Anonymous
Anonymous

Reputation: 86203

    String dateString = "2020-04-23T10:51:24.238+01:00";    

    Instant deserializedInstant = DateTimeFormatter.ISO_OFFSET_DATE_TIME
            .parse(dateString, Instant::from);
    System.out.println(deserializedInstant);

Output is:

2020-04-23T09:51:24.238Z

It works for your other string too:

    String dateString = "2019-11-11T15:44:10.201Z";

2019-11-11T15:44:10.201Z

Your JSON library may have still more elegant solutions. If not, you can probably wrap the above in a custom JSON deserializer.

Upvotes: 1

Smutje
Smutje

Reputation: 18123

Also Is there any way to deserialize java.util.Date into java.time.Instant

Know your API:

final java.util.Date date = new Date();
final java.time.Instant instant = date.toInstant();

Upvotes: 0

Related Questions