Home > Java > javaTutorial > body text

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

Susan Sarandon
Release: 2024-11-06 07:08:02
Original
423 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

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!