Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make default time zone apply in Spring Boot Jackson Date serialization

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" 
like image 202
codependent Avatar asked Sep 11 '17 08:09

codependent


People also ask

What is the default Date format in Jackson?

It's important to note that Jackson will serialize the Date to a timestamp format by default (number of milliseconds since January 1st, 1970, UTC).

What is spring boot default timezone?

While run any application in JVM, JVM will take system default time zone. For example production server is running under PST timezone and spring boot application will start then application will take PST timezone by default.

Does spring use Jackson by default?

Spring Boot uses Jackson by default for serializing and deserializing request and response objects in your REST APIs. If you want to use GSON instead of Jackson then it's just a matter of adding Gson dependency in your pom. xml file and specifying a property in the application.


2 Answers

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

like image 130
Jaumzera Avatar answered Sep 30 '22 03:09

Jaumzera


Solved registering a Jackson2ObjectMapperBuilderCustomizer bean:

@Bean public Jackson2ObjectMapperBuilderCustomizer jacksonObjectMapperCustomization() {     return jacksonObjectMapperBuilder ->          jacksonObjectMapperBuilder.timeZone(TimeZone.getDefault()); } 
like image 28
codependent Avatar answered Sep 30 '22 04:09

codependent