Home  >  Article  >  Java  >  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?

Susan Sarandon
Susan SarandonOriginal
2024-11-06 07:08:02414browse

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:

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

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

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:

<code class="XML"><property name="hibernate.jdbc.time_zone" value="UTC"/></code>

Using Spring Boot

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

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

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.

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