首页 > Java > java教程 > 如何使用 JPA 和 Hibernate 以 UTC 格式存储日期/时间和时间戳?

如何使用 JPA 和 Hibernate 以 UTC 格式存储日期/时间和时间戳?

Susan Sarandon
发布: 2024-11-06 07:08:02
原创
610 人浏览过

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

使用 JPA 和 Hibernate 以 UTC 格式存储日期/时间和时间戳

在 Java Persistence API (JPA) 和 Hibernate 中,管理日期/时间不同时区的时间戳值可能是一个挑战。为了确保 UTC(协调世界时)时间的存储和检索一致,正确配置框架至关重要。

考虑提供的带注释的 JPA 实体:

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

    @Temporal(TemporalType.TIMESTAMP)
    public java.util.Date date;
}</code>
登录后复制

存储日期/time UTC 时区,hibernate.jdbc.time_zone 属性可以配置如下:

使用 Properties.xml

properties.xml JPA 配置文件中,添加以下属性:

<code class="XML"><property name="hibernate.jdbc.time_zone" value="UTC"/></code>
登录后复制

使用 Spring Boot

如果使用 Spring Boot,请将此属性添加到您的 application.properties 文件中:

<code class="Properties">spring.jpa.properties.hibernate.jdbc.time_zone=UTC</code>
登录后复制

通过此配置,日期和时间戳将以 UTC 时区存储和检索。例如,如果日期是 2008-02-03 9:30am 太平洋标准时间 (PST),它将在数据库中存储为 2008-02-03 5:30pm UTC。检索时,它将被解释为 UTC 时间,因此即使转换为另一个时区,下午 5:30 UTC 仍然是下午 5:30 UTC。

以上是如何使用 JPA 和 Hibernate 以 UTC 格式存储日期/时间和时间戳?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板