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!