Search code examples
jsonspring-mvcjacksonjackson2

Wrong time when using @JsonFormat (+1 hour)


I have a class that contains the following attribute:

@JsonFormat(pattern= "yyyy/MM/dd hh:mm")
    private java.util.Date begin;

Now I do a POST to my rest service:

mockMvc.perform(post("/rest/foo")
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON)
                .content("{ \"begin\": \"2016/12/04 10:20\" }")
                .andExpect(status().isOk())
                .andReturn();

Finally the "begin" variable has value: Sun Dec 04 11:20:00 CET 2016

So somehow the JSON to object mapping adds one hour.

One solution is to use:

@JsonFormat(pattern= Constants.TIMESTAMP_FORMAT, timezone = "CET")
private Date begin;

But in summer we have CEST, so I cannot hardcode the time zone.

Any solutions? Thanks!

Btw: Originally the date comes from jquery datetimepicker.


Solution

  • When we need to internationalize our code and deploy in any server located in any part of world or when we need to handle timezone changes such as CET to CEST, then using timezone like this will not help, instead use the below approach

    In this approach timezone is retrieved from the server and feeded to jackson

    <bean name="timeZone" class="java.util.TimeZone" factory-method="getDefault"></bean>
    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="objectMapper">
           <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
               <property name="timeZone" ref="timeZone"></property>
           </bean>
        </property>
    </bean>