【问题标题】:Getting date in UTC timezone when using Hibernate使用 Hibernate 时获取 UTC 时区的日期
【发布时间】:2016-04-05 01:28:00
【问题描述】:

我在我的项目中使用 Spring Boot 和 Hibernate 5 以及 MySQL。

如何从 UTC 而非我的 JVM 时区的数据库中获取 DateTime?

是否有任何配置可以添加到 application.properties 中,例如 jadira.usertype.javaZone 用于 Jadira 或其他一些技巧?

【问题讨论】:

  • 你知道数据库中的时区吗?

标签: java spring hibernate datetime


【解决方案1】:

当您启动应用程序时,您可以将 JVM 的默认时区设置为 UTC

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

这将确保日期在您的应用程序中移动、保存到 db、从 db 中检索等时始终采用 UTC。并且可以在需要时转换为任何所需的时区。

【讨论】:

    【解决方案2】:

    从 Hibernate 5.2 开始,您现在可以使用 hibernate.jdbc.time_zone 配置属性。

    基本上,您现在可以使用以下配置属性为所有 TIMESTAMPTIME 列强制使用 UTC 时区:

    <property name="hibernate.jdbc.time_zone" value="UTC"/>
    

    【讨论】:

    • 如何用注解做到这一点?
    • 您不需要使用注释。这是一个全局设置。
    • 我在设置上述属性时使用 Hibernate 作为 JPA 供应商适配器我收到错误作为无效的 peroperty ` `
    • 那是因为你没有使用jpaProperties。你读过 Spring 框架手册吗?
    • 谢谢我已经完成了正确的配置并且时区现在可以工作了。 &lt;bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" p:packagesToScan="service.slicing.model" p:dataSource-ref="dataSource"&gt; &lt;property name="jpaVendorAdapter"&gt; &lt;bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"&gt; &lt;/bean&gt; &lt;/property&gt; &lt;property name="jpaProperties"&gt; &lt;props&gt; &lt;prop key="hibernate.jdbc.time_zone"&gt;UTC&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;/bean&gt;
    【解决方案3】:

    您可以从数据库中获取日期并将其转换为 UTC

    Date localTime = getDateFromDB();
    String format = "yyyy/MM/dd HH:mm:ss";
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date gmtTime = new Date(sdf.format(localTime));
    

    【讨论】:

      【解决方案4】:

      要为所有日期字段设置 UTC,请将以下字段添加到 MySQL 连接字符串:

      useTimezone=true
      serverTimezone=UTC
      useLegacyDatetimeCode=false
      

      示例连接字符串:

      jdbc:mysql://hostname/databaseName?useTimezone=true&amp;serverTimezone=UTC&amp;useLegacyDatetimeCode=false
      

      使用 jadira 用户类型为特定字段设置 UTC

      @Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime",
          parameters = { @Parameter(name = "databaseZone", value = "UTC")})
      private DateTime dateTime;
      

      【讨论】:

        【解决方案5】:

        感谢大家的帮助,我尝试了 Arul Kumaran 和 Sanj 解决方案,但效果不佳。所以我选择将日期存储为 varchar 并使用转换器将其作为 ZonedDateTime

        【讨论】:

          猜你喜欢
          • 2014-02-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-01-03
          • 1970-01-01
          • 2019-06-15
          相关资源
          最近更新 更多