我有一个表,其中包含数据类型为 DATETIME 的字段。我使用 java 在此表中保留一条记录,并按如下方式计算当前日期。
Date date = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime();
但是当我检查我的表时,它再次将这个时间转换为本地时区。
谁能给我解释一下,如何在数据库中以 UTC 时区存储日期。
@代码
我有一个数据库实体“Referral”对应于日期成员数据类型为 java.util.Date 的表,并使用 hibernate 保存它。
Referral ref = new Referral();
ref.setCreationDate(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime());
referralDAO.save(ref);
谢谢
吉腾德拉
最佳答案
MySql DATETIME 以与时区无关的方式存储。它只存储年/月/日/时/分/秒
如何解释该信息取决于您和您的应用程序。 如果您将其存储为 UTC,那么当您检索它时,您必须确保也将其解释为 UTC。
您可能对这个 SO 问题感兴趣:How can I get the current date and time in UTC or GMT in Java?
如该问题的答案中所述:
java.util.Date is always in UTC. What makes you think it's in local time? I suspect the problem is that you're displaying it via an instance of Calendar which uses the local timezone, or possibly using Date.toString() which also uses the local timezone.
关于java - mysql中的UTC日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6099753/