mysql中UTC日期
我有一个表,其中包含数据类型为 DATETIME 的字段.我使用 java 在此表中保留一条记录,并按如下方式计算当前日期.
I have a table which has field with data type as DATETIME. I persist a record in this table using java and I calculate current date as as following.
Date date = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime();
但是当我检查我的表时,它再次将这个时间转换为本地时区.
But When I check my table, it again converts this time into local timezone.
谁能给我解释一下,如何在数据库中以 UTC 时区存储日期.
Can some one please explain to me, how to store date in UTC timezone in database.
@代码
我有一个数据库实体 'Referral' 对应于日期成员数据类型为 java.util.Date 的表,并使用休眠来保存它.
I have a db entity 'Referral' corresponding to table with date member data type as java.util.Date and using hibernate to save it.
Referral ref = new Referral();
ref.setCreationDate(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime());
referralDAO.save(ref);
谢谢
吉腾德拉
推荐答案
MySql DATETIME 以与时区无关的方式存储.它只存储年/月/日/小时/分钟/秒
MySql DATETIME is stored in a time zone agnostic manner. It just stores year/month/day/hour/minute/second
您如何解释该信息取决于您和您的应用程序.如果您将其存储为 UTC,那么当您检索它时,您必须确保也将其解释为 UTC.
How you interpret that information is up to you and your application. If you are storing it as UTC, then when you retrieve it you must make sure to interpret it as UTC as well.
您可能对这个 SO 问题感兴趣:如何在 Java 中获取 UTC 或 GMT 的当前日期和时间?
You might be interested in this SO question: How can I get the current date and time in UTC or GMT in Java?
正如该问题的答案所述:
As mentioned in the answer to that question:
java.util.Date 是 always 在 UTC 中.是什么让你认为它在本地时间?我怀疑问题是您正在通过实例显示它使用本地的日历时区,或可能使用Date.toString() 也使用当地时区.
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.
相关文章