Date in UTC in mysql

最后都变了- 提交于 2019-12-30 07:00:47

问题


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.

Can some one please explain to me, how to store date in UTC timezone in database.

@Code

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);

Thanks

Jitendra


回答1:


MySql DATETIME is stored in a time zone agnostic manner. It just stores year/month/day/hour/minute/second

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.

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 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.




回答2:


Date in Java is just a long. It is agnostic of any time zones. When you pass your Date/Timestamp to the database via JDBC driver, it interprets it as time in the session time zone which is your JVM time zone.

Some databases, like Oracle and PostgreSQL, have data type TIMESTAMP WITH TIMEZONE. I don't believe MySQL has it. You can either switch your JVM time zone to UTC or use a string field and format your Date with SimpleDateFormat.



来源:https://stackoverflow.com/questions/6099753/date-in-utc-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!