"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 and Timestamps in UTC with JPA and Hibernate?

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

Published on 2024-11-08
Browse:199

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

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

In Java Persistence API (JPA) and Hibernate, managing date/time and timestamp values across different time zones can be a challenge. To ensure consistent storage and retrieval of UTC (Coordinated Universal Time) time, it is crucial to configure the framework appropriately.

Consider the annotated JPA entity provided:

public class Event {
    @Id
    public int id;

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

To store the date/time in UTC time zone, the hibernate.jdbc.time_zone property can be configured as follows:

Using Properties.xml

In the properties.xml JPA configuration file, add the following property:

Using Spring Boot

If using Spring Boot, add this property to your application.properties file:

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

With this configuration, dates and timestamps will be stored and retrieved in UTC time zone. For example, if the date is 2008-02-03 9:30am Pacific Standard Time (PST), it will be stored as 2008-02-03 5:30pm UTC in the database. When retrieved, it will be interpreted as UTC time, so 5:30pm UTC remains 5:30pm UTC even after conversion to another time zone.

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