JPA / Hibernate存储日期为UTC时区 [英] JPA/Hibernate store date in UTC time zone

查看:307
本文介绍了JPA / Hibernate存储日期为UTC时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将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;
}

如果日期是2008年-2月03日太平洋标准时间PST),那么我想要UTC-2008-Feb-03 5:30 pm存储在数据库中。同样,当从数据库检索日期时,我希望将其解释为UTC。所以在这种情况下,530pm是UTCpm 530pm。显示时将格式化为PST上午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.

推荐答案

据我所知,您需要将整个Java应用程序在UTC时区(以便Hibernate将以UTC存储日期),您需要转换为任何时区,当您显示东西(至少我们这样做)。

To the best of my knowledge, you need to put your entire Java app in UTC timezone (so that Hibernate will store dates in UTC), and you'll need to convert to whatever timezone desired when you display stuff (at least we do it this way).

在启动时,我们做:

TimeZone.setDefault(TimeZone.getTimeZone("Etc/UTC"));

并将所需的时区设置为DateFormat:

And set the desired timezone to the DateFormat:

fmt.setTimeZone(TimeZone.getTimeZone("Europe/Budapest"))

这篇关于JPA / Hibernate存储日期为UTC时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆