Search code examples
javajsonjacksontimezonejackson2

Jackson jsonformat deserialize always in UTC


Jackson's jsonformat annotation works not quite as I expected.

Let's say in Java SimpleDateFormat:

SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
Date date = sdf.parse("1-Mar-2018");

The date object value is 1-Mar-2018 SGT. Which is fine because my timezone is in Singapore.

Now I have a http webservice which post a json value:

{
  "filterDate": "01-Mar-2018"
}

In my bean, I annotate it with

@JsonFormat(pattern = "dd-MMM-yyyy")
public void setDeliveryDate(Date deliveryDate) {
    this.deliveryDate = deliveryDate;
}

OK the value of deliveryDate is 1-Mar-2018 UTC.

While I do this:

@JsonFormat(pattern = "dd-MMM-yyyy", timezone="Asia/Singapore")
public void setDeliveryDate(Date deliveryDate) {
    this.deliveryDate = deliveryDate;
}

It is still deserialized into 1-Mar-2018 UTC, which I think it should be 1-Mar-2018 SGT.

Why this behave like this?


Solution

  • timezone parameter is meant for serialisation according to JsonFormat documentation and not for deserialisation as in your post. I don't see how it could be used for deserialisation given that Date "is intended to reflect coordinated universal time (UTC)" and doesn't contain timezone information.

    Consider switching to ZonedDateTime, available since Java 8, if you want to specify a timezone for deliveryDate.

    If you must use Date you can specify a default timezone that will be used whenever you print or format any Date object E.g.

    TimeZone.setDefault(TimeZone.getTimeZone("Asia/Singapore"));
    System.out.println(new Date());
    

    produces

    Tue Mar 06 21:15:12 SRET 2018