问题
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