28

I have configured my Spring Boot application to serialize dates as ISO8601 strings:

spring:
  jackson:
    serialization:
      write-dates-as-timestamps: false

This is what I am getting:

"someDate": "2017-09-11T07:53:27.000+0000"

However my time zone is Europe/Madrid. In fact if I print TimeZone.getDefault() that's what I get.

How can I make Jackson serialize those datetime values using the actual timezone? GMT+2

"someDate": "2017-09-11T09:53:27.000+0200"
codependent
  • 20,799
  • 23
  • 140
  • 264

4 Answers4

33

Solved registering a Jackson2ObjectMapperBuilderCustomizer bean:

@Bean
public Jackson2ObjectMapperBuilderCustomizer jacksonObjectMapperCustomization() {
    return jacksonObjectMapperBuilder -> 
        jacksonObjectMapperBuilder.timeZone(TimeZone.getDefault());
}
codependent
  • 20,799
  • 23
  • 140
  • 264
33

I found myself with the same problem. In my case, I have only one timezone for my app, then adding:

spring.jackson.time-zone: America/Sao_Paulo

in my application.properties solved the problem.

Source: https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html#JACKSON

Jaumzera
  • 2,158
  • 24
  • 42
31

You can set timezone for whole application with adding this to a config class:

@PostConstruct
void started() {
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}
barbakini
  • 2,784
  • 2
  • 18
  • 24
  • 2
    Jackson won't pick that up. The default TimeZone is the right one. My solution solves it. Thanks anyway – codependent Sep 11 '17 at 12:56
  • 4
    @codependent I use jackson in my project too and this configuration solved my problem for time zones. Anyway if you solve your problem, nothing to argue :) I will just leave my post if anybody can use it. Happy coding. – barbakini Sep 11 '17 at 16:06
  • yes this will work, it depends where in your application you are setting default time zone. this work's good because now ur application will not do any time adjustment. – Arun Pratap Singh Jun 01 '18 at 07:23
  • This sets the "target" timezone of (de)serialization, while the `JsonFormat(timezone = "xxx")` sets the input timezone of (de)serialization when parsing as well as formating. See [another question of mine](https://stackoverflow.com/questions/53322376/simpledateformat-with-timezone-set-gets-correct-value-but-wrong-zone?noredirect=1#answer-53337257) for details. – WesternGun Nov 19 '18 at 08:47
5

There are 2 solutions for this:

1. Add JSON format annotation

@JsonFormat(shape = JsonFormat.Shape.STRING, timezone = "Asia/Kolkata")
private Date insertionTime;

2. Add Jackson time zone to properties (spring boot)

spring.jackson.time-zone: America/Sao_Paulo

Reference : https://www.baeldung.com/spring-boot-formatting-json-dates

Pramod H G
  • 1,208
  • 12
  • 14