如何使用 JPA 和 Hibernate 在 UTC 时区中存储日期/时间和时间戳 [英] How to store date/time and timestamps in UTC time zone with JPA and Hibernate
问题描述
如何配置 JPA/Hibernate 以将日期/时间作为 UTC (GMT) 时区存储在数据库中?考虑这个带注释的 JPA 实体:
How can I configure JPA/Hibernate to store a date/time in the database as UTC (GMT) time zone? Consider this annotated JPA entity:
public class Event {
@Id
public int id;
@Temporal(TemporalType.TIMESTAMP)
public java.util.Date date;
}
如果日期是太平洋标准时间 (PST) 的 2008-Feb-03 上午 9:30,那么我希望将 2008-Feb-03 下午 5:30 的 UTC 时间存储在数据库中.同样,当从数据库中检索日期时,我希望将其解释为 UTC.所以在这种情况下,530pm 是 530pm UTC.显示时将格式化为太平洋标准时间上午 9:30.
If the date is 2008-Feb-03 9:30am Pacific Standard Time (PST), then I want the UTC time of 2008-Feb-03 5:30pm stored in the database. Likewise, when the date is retrieved from the database, I want it interpreted as UTC. So in this case 530pm is 530pm UTC. When it's displayed it will be formatted as 9:30am PST.
推荐答案
从 Hibernate 5.2 开始,您现在可以通过将以下配置属性添加到 properties.xml
JPA 配置文件中来强制使用 UTC 时区:
Since Hibernate 5.2, you can now force the UTC time zone by adding the following configuration property into the properties.xml
JPA configuration file:
<property name="hibernate.jdbc.time_zone" value="UTC"/>
如果您使用的是 Spring Boot,则将此属性添加到您的 application.properties
文件中:
If you're using Spring Boot, then add this property to your application.properties
file:
spring.jpa.properties.hibernate.jdbc.time_zone=UTC
这篇关于如何使用 JPA 和 Hibernate 在 UTC 时区中存储日期/时间和时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!