使用HIbernate从DB检索日期时获取错误的datetime字段值[duplicate]

时间:2021-11-25 22:19:09

This question already has an answer here:

这个问题在这里已有答案:

I am using Hibernate 4.3.2. I want to store all my dates in UTC in database. I am able to store date in UTC. Now I am retrieving date from database using below method.

我正在使用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
}

As I mentioned I am getting different date in output which is stored in database. I am not getting reason why?

Some steps I did to configure UTC timezone.
1. TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
2. System.setProperty("user.timezone", "UTC");
3. I also set my database timezone in UTC.

正如我所提到的,我在输出中得到的日期不同,存储在数据库中。我没理由为什么?我做了一些配置UTC时区的步骤。 1. TimeZone.setDefault(TimeZone.getTimeZone(“UTC”)); 2. System.setProperty(“user.timezone”,“UTC”); 3.我还将我的数据库时区设置为UTC。

1 个解决方案

#1


0  

This is due to Timezone offset being added to your date object. Try the below code

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

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

#1


0  

This is due to Timezone offset being added to your date object. Try the below code

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

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