問題描述
我有一個表,其中包含數據類型為 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.
這篇關于mysql中UTC日期的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!