Set Jackson Timezone for Date deserialization

JsonSpring MvcJackson

Json Problem Overview


I'm using Jackson (via Spring MVC Annotations) to deserialize a field into a java.util.Date from JSON. The POST looks like - {"enrollDate":"2011-09-28T00:00:00.000Z"}, but when the Object is created by Spring & Jackson it sets the date as "2011-09-27 20:00:00".

How can I set the proper timezone in Jackson? Or if that is not the problem, how do I send EST from the JSON message?

Javascript/jQuery:

var personDataView = { enrollDate : new Date($("#enrollDate").val()), 
			           //...other members
                      };

			
$.postJSON('/some/path/', personDataView, function(data){
    //... handle the response here

});

JSON Message:

{"enrollDate":"2011-09-28T00:00:00.000Z"}

Spring Controller:

@RequestMapping(value="/", method=RequestMethod.POST)
public @ResponseBody String saveProfile(@RequestBody personDataView persondataView, HttpServletRequest request)
{
        //...dataView has a java.util.Date enrollDate field
        //...other code
}

Json Solutions


Solution 1 - Json

In Jackson 2+, you can also use the @JsonFormat annotation:

@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone="America/Phoenix")
private Date date;

If it doesn't work this way then try wrapping Z with single quotes, i.e. pattern="yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

Solution 2 - Json

Have you tried this in your application.properties?

spring.jackson.time-zone= # Time zone used when formatting dates. For instance `America/Los_Angeles`

Solution 3 - Json

If you really want Jackson to return a date with another time zone than UTC (and I myself have several good arguments for that, especially when some clients just don't get the timezone part) then I usually do:

ObjectMapper mapper = new ObjectMapper();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
dateFormat.setTimeZone(TimeZone.getTimeZone("CET"));
mapper.getSerializationConfig().setDateFormat(dateFormat);
// ... etc

It has no adverse effects on those that understand the timezone-p

Solution 4 - Json

I am using Jackson 1.9.7 and I found that doing the following does not solve my serialization/deserialization timezone issue:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
objectMapper.setDateFormat(dateFormat);

Instead of "2014-02-13T20:09:09.859Z" I get "2014-02-13T08:09:09.859+0000" in the JSON message which is obviously incorrect. I don't have time to step through the Jackson library source code to figure out why this occurs, however I found that if I just specify the Jackson provided ISO8601DateFormat class to the ObjectMapper.setDateFormat method the date is correct.

Except this doesn't put the milliseconds in the format which is what I want so I sub-classed the ISO8601DateFormat class and overrode the format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) method.

/**
 * Provides a ISO8601 date format implementation that includes milliseconds
 *
 */
public class ISO8601DateFormatWithMillis extends ISO8601DateFormat {

  /**
   * For serialization
   */
  private static final long serialVersionUID = 2672976499021731672L;

  
  @Override
  public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition)
  {
      String value = ISO8601Utils.format(date, true);
      toAppendTo.append(value);
      return toAppendTo;
  }
}

Solution 5 - Json

Looks like older answers were fine for older Jackson versions, but since objectMapper has method setTimeZone(tz), setting time zone on a dateFormat is totally ignored.

How to properly setup timeZone to the ObjectMapper in Jackson version 2.11.0:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setTimeZone(TimeZone.getTimeZone("Europe/Warsaw"));

Full example

  @Test
  void test() throws Exception {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.findAndRegisterModules();
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    JavaTimeModule module = new JavaTimeModule();
    objectMapper.registerModule(module);
    objectMapper.setTimeZone(TimeZone.getTimeZone("Europe/Warsaw"));

    ZonedDateTime now = ZonedDateTime.now();
    String converted = objectMapper.writeValueAsString(now);

    ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
    System.out.println("serialized: " + now);
    System.out.println("converted: " + converted);
    System.out.println("restored: " + restored);

    Assertions.assertThat(now).isEqualTo(restored);
  }
`

Solution 6 - Json

Just came into this issue and finally realised that LocalDateTime doesn't have any timezone information. If you received a date string with timezone information, you need to use this as the type:

ZonedDateTime

Check this link

Solution 7 - Json

Your date object is probably ok, since you sent your date encoded in ISO format with GMT timezone and you are in EST when you print your date.

Note that Date objects perform timezone translation at the moment they are printed. You can check if your date object is correct with:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
cal.setTime(date);
System.out.println (cal);

Solution 8 - Json

I had same problem with Calendar deserialization, solved extending CalendarDeserializer.
It forces UTC Timezone
I paste the code if someone need it:

@JacksonStdImpl
public class UtcCalendarDeserializer extends CalendarDeserializer {

	TimeZone TZ_UTC = TimeZone.getTimeZone("UTC");

	@Override
	public Calendar deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
		JsonToken t = jp.getCurrentToken();
		if (t == JsonToken.VALUE_NUMBER_INT) {
			Calendar cal = Calendar.getInstance(TZ_UTC);
			cal.clear();
			cal.setTimeInMillis(jp.getLongValue());

			return cal;
		}

		return super.deserialize(jp, ctxt);
	}
}

in JSON model class just annotate the field with:

@JsonDeserialize(using = UtcCalendarDeserializer.class)
private Calendar myCalendar;

Solution 9 - Json

For anyone struggling with this problem in the now (Feb 2020), the following Medium post was crucial to overcoming it for us.

https://medium.com/@ttulka/spring-http-message-converters-customizing-770814eb2b55

In our case, the app uses @EnableWebMvc and would break if removed so, the section on 'The Life without Spring Boot' was critical. Here's what ended up solving this for us. It allows us to still consume and produce JSON and XML as well as format our datetime during serialization to suit the app's needs.

@Configuration
@ComponentScan("com.company.branch")
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(0, new MappingJackson2XmlHttpMessageConverter(
                new Jackson2ObjectMapperBuilder()
                        .defaultUseWrapper(false)
                        .createXmlMapper(true)
                        .simpleDateFormat("yyyy-mm-dd'T'HH:mm:ss'Z'")
                        .build()
        ));
    converters.add(1, new MappingJackson2HttpMessageConverter(
                new Jackson2ObjectMapperBuilder()
                        .build()
        ));
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMike GView Question on Stackoverflow
Solution 1 - JsonOlivier LecrivainView Answer on Stackoverflow
Solution 2 - Jsonuser1941489View Answer on Stackoverflow
Solution 3 - JsonSiCNView Answer on Stackoverflow
Solution 4 - JsonwhitestryderView Answer on Stackoverflow
Solution 5 - JsonLukaszHView Answer on Stackoverflow
Solution 6 - JsonLichaderView Answer on Stackoverflow
Solution 7 - JsonjjmontesView Answer on Stackoverflow
Solution 8 - Jsonfl4lView Answer on Stackoverflow
Solution 9 - JsonrobridesView Answer on Stackoverflow