Home > Java > javaTutorial > body text

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

Barbara Streisand
Release: 2024-10-31 16:46:30
Original
695 people have browsed it

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

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

When working with temporal data in database systems, it's essential to consider the time zone in which the data is stored and interpreted. For applications that require consistent date and time handling across multiple time zones, using the Coordinated Universal Time (UTC) time zone provides a standard reference.

To configure JPA and Hibernate to store and retrieve date/time values as UTC, regardless of the local time zone, the following steps can be taken:

JPA Entity Configuration:

<code class="java">public class Event {
    @Id
    public int id;

    @Temporal(TemporalType.TIMESTAMP)
    @TimeZone(value = TimeZone.UTC)
    public java.util.Date date;
}</code>
Copy after login

By adding @TimeZone(value = TimeZone.UTC) to the annotated date field, you explicitly specify that the date should be interpreted and stored in UTC time.

Hibernate Configuration for UTC Time Zone:

Hibernate 5.2 and Above:

In Hibernate 5.2 and later versions, you can override the default system time zone used by Hibernate by configuring the hibernate.jdbc.time_zone property in your JPA configuration file (properties.xml):

<code class="xml"><property name="hibernate.jdbc.time_zone" value="UTC"/></code>
Copy after login

Spring Boot Applications:

If you're using Spring Boot, you can set the above property in your application.properties file:

<code class="properties">spring.jpa.properties.hibernate.jdbc.time_zone=UTC</code>
Copy after login

Example:

Consider the JPA entity defined in the example. If the date field is set to 2008-Feb-03 9:30am PST (Pacific Standard Time), Hibernate will store the value as 2008-Feb-03 5:30pm UTC in the database. This ensures that the time is consistently stored and retrieved in the UTC time zone, regardless of the server or local time zone settings.

The above is the detailed content of How to Store Date/Time and Timestamps in UTC Time Zone with JPA and Hibernate?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!