user3697919
user3697919

Reputation: 303

in Java 8, how to serialize/deserialize a date time information with time zone

I would like to deserilize a json string with datetime information such as 2016-07-22T11:20:48.430-07:00 to a date time object using Jackson, currently, I am using joda Datetime, it works fine, I was able to convert 2016-07-22T11:20:48.430-07:00 to Datetime (UTC).

However, I want to use java 8 date time object, any recommendation? localDateTime do not have time zone information, and zoneDateTime seems not be able to deal with format like: 2016-07-22T11:20:48.430-07:00

Upvotes: 2

Views: 3560

Answers (1)

Basil Bourque
Basil Bourque

Reputation: 338181

OffsetDateTime

Your input strings have an offset-from-UTC not a time zone. A time zone is an offset plus a set of rules for handling anomalies such as Daylight Saving Time (DST).

For date-time values with an offset, use the aptly named OffsetDateTime class.

OffsetDateTime odt = OffsetDateTime.parse( "2016-07-22T11:20:48.430-07:00" );

You can apply a full time zone if desired.

ZoneId zoneId = ZoneId.of( "Europe/Paris" );
ZonedDateTime zdt = odt.atZone( zoneId );

For UTC value, extract an Instant.

Instant instant = odt.toInstant();

Adapter library

I don't use Jackson myself but I know you can use various adapter classes to handle java.time classes. See the first comment on the Question for one. See this Answer on a similar Question for another.

Hopefully Jackson will eventually be modernized to handle these types directly.

Upvotes: 1

Related Questions