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

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

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 21:01:30328browse

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>

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>

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

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

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!

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