Spring REST LocalDate UTC differs of one day

痞子三分冷 提交于 2019-11-29 16:22:06

I agree with the author of this article The 5 laws of API dates and times that we have to store and return time in UTC. And 'front-end' must decide itself how to convert the time value depending on the client time-zone.

To achieve this (store and return time in UTC) we set JVM parameter -Duser.timezone=UTC or add spring.jpa.properties.hibernate.jdbc.time_zone=UTC to application.properties (starting from Hibernate 5.2.3.Final). Then change time fields of our entities from LocalDateTime (that doesn't store time-zone info) to ZonedDateTime type.

After that the time values will be stored in UTC independently from the local time-zone of the computer where the application is started and SDR will return these values in ISO8601 form: 2017-07-02T11:58:10.089Z

But if it's necessary to return time values in the specific time-zone we have to setup @JsonFormat annotation to all of our time fields:

@JsonFormat(timezone = "Europe/Rome", pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
private ZonedDateTime createdDate;

Our we can define constant TIME_ZONE in our application and set it in @JsonFormat annotations: @JsonFormat(timezone = Application.TIME_ZONE, ...).

Then we get this output:

{
    //...
    "createdDate": "2017-07-02T14:11:45.964+0200",
    //...
}

Unfortunately, parameter spring.jackson.time-zone (based on my short investigation) affects only on service messages in the application, for example:

{
    "timestamp": "2017-07-02T14:14:09.486+0200",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/users"
}

To get time here in 'zoned' form we have to set properly spring.jackson.date-format parameter in the application.properties:

spring.jackson.date-format=com.fasterxml.jackson.databind.util.StdDateFormat
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!