Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default timezone for DateTime deserialization with Jackson (Joda-Time module)

This question is about deserialization to Joda-Time DateTime using jackson-datatype-joda module for Jackson. Is there a default timezone that date strings will be deserialized into? If so, what is it? Is it UTC?

I need to ask this because the Jackson documentation is not specific for Joda-Time DateTime. I found in this article (http://wiki.fasterxml.com/JacksonFAQDateHandling) that Jackson will assume GMT as the default time zone for deserializing into java.util.Date or java.util.Calendar. However, there is no mention of Joda-Time data types in this document. In addition, I specifically need strings to deserialize into DateTime objects using the UTC timezone, not GMT: although these two zones are very similar, there are some small differences and therefore GMT will not be feasible for me.

Thank you.

like image 961
ecbrodie Avatar asked Nov 26 '13 16:11

ecbrodie


People also ask

Does Joda DateTime have timezone?

Adjusting Time ZoneUse the DateTimeZone class in Joda-Time to adjust to a desired time zone. Joda-Time uses immutable objects. So rather than change the time zone ("mutate"), we instantiate a new DateTime object based on the old but with the desired difference (some other time zone). Use proper time zone names.

How do I change the date format in object mapper?

We can format a date using the setDateFormat() of ObjectMapper class. This method can be used for configuring the default DateFormat when serializing time values as Strings and deserializing from JSON Strings.


1 Answers

The source code for DateTimeDeserializer shows it uses the timezone from DeserializationContext which is provided by ObjectMapper during deserialization. If you look at ObjectMapper API, you will see there is method for setting the timezone:

public ObjectMapper setTimeZone(TimeZone tz)

Thus you can use this method to configure your ObjectMapper and set the timezone to the correct one.

For what concerns the default value, it seems the Javadoc says one thing, but the code shows another.

Javadoc for ObjectMapper.setTimeZone(TimeZone tz):

/**
  * Method for overriding default TimeZone to use for formatting.
  * Default value used is {@link TimeZone#getDefault()}.
  */

However, the code sets the timezone explicitly on:

protected final static BaseSettings DEFAULT_BASE = new BaseSettings(
    ...
    // TimeZone.getDefault()
    TimeZone.getTimeZone("GMT"),
    ...

So, apparently, it actually uses GMT, and not the default JVM default.

I would say that probably the best choice would be not relying on this and set it by yourself on ObjectMapper.setTimeZone(TimeZone tz).

like image 147
Redder Avatar answered Oct 06 '22 04:10

Redder