"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Store Date/Time in UTC with JPA and Hibernate?

How to Store Date/Time in UTC with JPA and Hibernate?

Published on 2024-11-09
Browse:633

How to Store Date/Time in UTC with JPA and Hibernate?

Storing Date/Time in UTC Time Zone with JPA and Hibernate

Concerned about time zone discrepancies when handling date and time in your JPA/Hibernate applications? This article explores how to effectively store and retrieve temporal data in UTC (GMT) time zone, ensuring consistent and accurate handling across different time zones.

Consider the annotated JPA entity below:

public class Event {
    @Id
    public int id;

    @Temporal(TemporalType.TIMESTAMP)
    public java.util.Date date;
}

To ensure that the stored date reflects UTC time:

Solution:

Since Hibernate 5.2, configuring the UTC time zone is simplified. By adding the following property to your JPA configuration file (properties.xml):

or for Spring Boot applications, adding this property to application.properties:

spring.jpa.properties.hibernate.jdbc.time_zone=UTC

This configuration ensures that all temporal data is stored and retrieved in UTC time zone. For example, the date 2008-Feb-03 9:30am Pacific Standard Time (PST) will be stored as 2008-Feb-03 5:30pm UTC in the database and interpreted as such when retrieved.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3