Home > Java > javaTutorial > How to Store Date/Time in UTC with JPA and Hibernate?

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

Barbara Streisand
Release: 2024-11-02 21:01:30
Original
477 people have browsed it

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:

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

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

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):

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

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

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

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.

The above is the detailed content of How to Store Date/Time in UTC 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