Spring REST LocalDate UTC differs of one day

前端 未结 1 1271
暗喜
暗喜 2020-12-22 03:22

I\'m using Spring Boot 1.5.4, Hibernate 5.2.10, Spring Data REST, HATEOAS, JDK8 with LocalDate and LocalDateTime. My computer is on CEST timezone but I want the application

相关标签:
1条回答
  • 2020-12-22 03:51

    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
    
    0 讨论(0)
提交回复
热议问题