【问题标题】:Getting wrong datetime field value while retrieving date from DB using HIbernate [duplicate]使用 HIbernate 从数据库中检索日期时获取错误的日期时间字段值 [重复]
【发布时间】:2014-06-10 17:35:51
【问题描述】:

我使用的是 Hibernate 4.3.2。我想将我所有的日期存储在数据库中的 UTC 中。我可以在 UTC 中存储日期。现在我正在使用以下方法从数据库中检索日期。

public void getLastActiveTimeAndCheckForIt(int pageId)
{
    Criteria criteria = getCurrentSession().createCriteria(MyTable.class, "myTable");
    criteria.add(Restrictions.eq("myTable.id", 1));
    MyTable row = (MyTable) criteria.uniqueResult();
    System.out.println(row.getUpdatedDateTime());
   //output : 2014-06-10 03:05:35.0 and actual date in database : 2014-06-10 08:35:35
}

正如我提到的,我在存储在数据库中的输出中得到了不同的日期。我不明白为什么?

我为配置 UTC 时区所做的一些步骤。
1. TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
2. System.setProperty("user.timezone", "UTC");
3. I also set my database timezone in UTC.

【问题讨论】:

  • 但是对象包含正确的值?也许失败发生在System.out.println 各自的toString()-日期方法中。
  • 嗨@Smutje,谢谢,但是如何调试对象值?
  • System.out.println(row.getUpdatedDateTime()); 设置断点并查看row 包含哪些值。
  • 嗨,我调试它..在地图中我得到相同的值。

标签: java mysql hibernate datetime timezone


【解决方案1】:

这是由于时区偏移被添加到您的日期对象。试试下面的代码

DateFormat converter = new SimpleDateFormat("dd/MM/yyyy:HH:mm:ss");
converter.setTimeZone(TimeZone.getDefault());
System.out.println(converter.format(row.getUpdatedDateTime()));

【讨论】:

  • 但为什么即使在我到处设置 UTC 时区之后,该偏移量仍会添加到 Date 对象中?
  • 哦..我是反过来读的。您的数据库值具有时区偏移量。(通过查看输出,DB 中的时区设置未反映)但是在 Java 中,当您将时区设置为 UTC 时,它会更正该偏移量并显示 GMT 时间。我已经编辑了答案。只需将时区设置为默认值以更安全。
猜你喜欢
  • 2019-08-23
  • 2016-08-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-30
  • 2016-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多