MYSQL時(shí)區(qū)導(dǎo)致時(shí)間差了14或13小時(shí)的解決方法
p>我一般使用MYSQL定義字段類型時(shí),一般使用TIMESTAMP時(shí)間戳來定義創(chuàng)建時(shí)間與更新時(shí)間,并將其定義為默認(rèn)值為CURRENT_TIME,但是由于場(chǎng)景特殊,現(xiàn)在我需要將一個(gè)任務(wù)的開始時(shí)間與結(jié)束時(shí)間記錄,并寫入數(shù)據(jù)庫(kù),那么我的開始時(shí)間戳與結(jié)束時(shí)間戳則不應(yīng)該是使用數(shù)據(jù)庫(kù)自帶的默認(rèn)值的,而是應(yīng)該使用我使用java代碼里面?zhèn)鬟M(jìn)去的LocalDateTime.now()方法。但是插入后數(shù)據(jù)我發(fā)現(xiàn)有問題,插入的時(shí)間比我當(dāng)前的實(shí)際時(shí)間少13個(gè)小時(shí)。于是我開始百度找到答案。
名為 CST 的時(shí)區(qū)是一個(gè)很混亂的時(shí)區(qū),在與 MySQL 協(xié)商會(huì)話時(shí)區(qū)時(shí),Java 會(huì)誤以為是 CST -0500,而非 CST +0800。
CST 時(shí)區(qū)
名為 CST 的時(shí)區(qū)是一個(gè)很混亂的時(shí)區(qū),有四種含義:
- 美國(guó)中部時(shí)間 Central Standard Time (USA) UTC-06:00
- 澳大利亞中部時(shí)間 Central Standard Time (Australia) UTC+09:30
- 中國(guó)標(biāo)準(zhǔn)時(shí) China Standard Time UTC+08:00
- 古巴標(biāo)準(zhǔn)時(shí) Cuba Standard Time UTC-04:00
今天是“4月28日”。為什么提到日期?因?yàn)槊绹?guó)從“3月11日”至“11月7日”實(shí)行夏令時(shí),美國(guó)中部時(shí)間改為 UTC-05:00,與 UTC+08:00 相差 13 小時(shí)。
排錯(cuò)過程
在項(xiàng)目中,偶然發(fā)現(xiàn)數(shù)據(jù)庫(kù)中存儲(chǔ)的 Timestamp 字段的 unix_timestamp() 值比真實(shí)值少了 13 個(gè)小時(shí)。通過調(diào)試追蹤,發(fā)現(xiàn)了 com.mysql.cj.jdbc 里的時(shí)區(qū)協(xié)商有問題。
當(dāng) JDBC 與 MySQL 開始建立連接時(shí),會(huì)調(diào)用 com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer() 獲取服務(wù)器參數(shù),其中我們看到調(diào)用 this.session.configureTimezone() 函數(shù),它負(fù)責(zé)配置時(shí)區(qū)。
public void configureTimezone() {
String configuredTimeZoneOnServer = getServerVariable("time_zone");
if ("SYSTEM".equalsIgnoreCase(configuredTimeZoneOnServer)) {
configuredTimeZoneOnServer = getServerVariable("system_time_zone");
}
String canonicalTimezone = getPropertySet().getStringReadableProperty(PropertyDefinitions.PNAME_serverTimezone).getValue();
if (configuredTimeZoneOnServer != null) {
// user can override this with driver properties, so don't detect if that's the case
if (canonicalTimezone == null || StringUtils.isEmptyOrWhitespaceOnly(canonicalTimezone)) {
try {
canonicalTimezone = TimeUtil.getCanonicalTimezone(configuredTimeZoneOnServer, getExceptionInterceptor());
} catch (IllegalArgumentException iae) {
throw ExceptionFactory.createException(WrongArgumentException.class, iae.getMessage(), getExceptionInterceptor());
}
}
}
if (canonicalTimezone != null && canonicalTimezone.length() > 0) {
this.serverTimezoneTZ = TimeZone.getTimeZone(canonicalTimezone);
// The Calendar class has the behavior of mapping unknown timezones to 'GMT' instead of throwing an exception, so we must check for this...
if (!canonicalTimezone.equalsIgnoreCase("GMT")
&& this.serverTimezoneTZ.getID().equals("GMT")) {
throw ...
}
}
this.defaultTimeZone = this.serverTimezoneTZ;
}復(fù)制代碼追蹤代碼可知,當(dāng) MySQL 的 time_zone 值為 SYSTEM 時(shí),會(huì)取 system_time_zone 值作為協(xié)調(diào)時(shí)區(qū)。
讓我們登錄到 MySQL 服務(wù)器驗(yàn)證這兩個(gè)值:
mysql> show variables like '%time_zone%'; +------------------+--------+ | Variable_name | Value | +------------------+--------+ | system_time_zone | CST | | time_zone | SYSTEM | +------------------+--------+ 2 rows in set (0.00 sec)復(fù)制代碼
重點(diǎn)在這里!若 String configuredTimeZoneOnServer 得到的是 CST 那么 Java 會(huì)誤以為這是 CST -0500,因此 TimeZone.getTimeZone(canonicalTimezone) 會(huì)給出錯(cuò)誤的時(shí)區(qū)信息。

debug variables
如圖所示,本機(jī)默認(rèn)時(shí)區(qū)是 Asia/Shanghai +0800,誤認(rèn)為服務(wù)器時(shí)區(qū)為 CST -0500,實(shí)際上服務(wù)器是 CST +0800。
我們會(huì)想到,即便時(shí)區(qū)有誤解,如果 Timestamp 是以 long 表示的時(shí)間戳傳輸,也不會(huì)出現(xiàn)問題,下面讓我們追蹤到 com.mysql.cj.jdbc.PreparedStatement.setTimestamp()。
public void setTimestamp(int parameterIndex, Timestamp x) throws java.sql.SQLException {
synchronized (checkClosed().getConnectionMutex()) {
setTimestampInternal(parameterIndex, x, this.session.getDefaultTimeZone());
}
}注意到這里 this.session.getDefaultTimeZone() 得到的是剛才那個(gè) CST -0500。
private void setTimestampInternal(int parameterIndex, Timestamp x, TimeZone tz) throws SQLException {
if (x == null) {
setNull(parameterIndex, MysqlType.TIMESTAMP);
} else {
if (!this.sendFractionalSeconds.getValue()) {
x = TimeUtil.truncateFractionalSeconds(x);
}
this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = MysqlType.TIMESTAMP;
if (this.tsdf == null) {
this.tsdf = new SimpleDateFormat("''yyyy-MM-dd HH:mm:ss", Locale.US);
}
this.tsdf.setTimeZone(tz);
StringBuffer buf = new StringBuffer();
buf.append(this.tsdf.format(x));
if (this.session.serverSupportsFracSecs()) {
buf.append('.');
buf.append(TimeUtil.formatNanos(x.getNanos(), true));
}
buf.append('\'');
setInternal(parameterIndex, buf.toString());
}
}原來 Timestamp 被轉(zhuǎn)換為會(huì)話時(shí)區(qū)的時(shí)間字符串了。問題到此已然明晰:
- JDBC 誤認(rèn)為會(huì)話時(shí)區(qū)在 CST-5
- JBDC 把 Timestamp+0 轉(zhuǎn)為 CST-5 的 String-5
- MySQL 認(rèn)為會(huì)話時(shí)區(qū)在 CST+8,將 String-5 轉(zhuǎn)為 Timestamp-13
最終結(jié)果相差 13 個(gè)小時(shí)!如果處在冬令時(shí)還會(huì)相差 14 個(gè)小時(shí)!
解決方案
解決辦法也很簡(jiǎn)單,明確指定 MySQL 數(shù)據(jù)庫(kù)的時(shí)區(qū),不使用引發(fā)誤解的 CST:
mysql> set global time_zone = '+08:00'; Query OK, 0 rows affected (0.00 sec) mysql> set time_zone = '+08:00'; Query OK, 0 rows affected (0.00 sec)復(fù)制代碼
或者修改 my.cnf 文件,在 [mysqld] 節(jié)下增加 default-time-zone = '+08:00'。
修改時(shí)區(qū)操作影響深遠(yuǎn),需要重啟 MySQL 服務(wù)器,建議在維護(hù)時(shí)間進(jìn)行。
JSR-310相關(guān)規(guī)范在這個(gè)版本就已經(jīng)支持了,所以大家只要不小于此版本的就放心用吧。舉個(gè)例子:
public class User {
private LocalDateTime createTime;
// setter ... getter ... 省略了哈
}
public interface UserDao {
@Insert("INSERT INTO user(create_time) values(#{createTime})")
int insertUser(User user);
}
// 在set時(shí)間時(shí),一般直接用now方法就好
user.setCreateTime(LocalDateTime.now());這樣就OK了,如果你數(shù)據(jù)庫(kù)表存的是datetime類型的話,MyBatis自動(dòng)幫你解析轉(zhuǎn)換,你不用做額外工作。
注意:
這里L(fēng)ocalDateTime默認(rèn)是不包含時(shí)區(qū)信息的,會(huì)取當(dāng)前機(jī)器時(shí)間的時(shí)區(qū),其實(shí)一般情況下,是沒有問題的,我用阿里云的服務(wù)器(在深圳),直接打印出來就是:
System.out.println(LocalDateTime.now()); // 輸出的是北京時(shí)間 2019-03-15T16:51:37.121
當(dāng)然這樣可能你不是很放心,那么就指明時(shí)區(qū):
System.out.println(LocalDateTime.now(ZoneId.of("+08:00")));MySQL時(shí)區(qū)有問題(相差13或14小時(shí))
這個(gè)問題最開始讓我非常頭疼,明明我的Tomcat和MySQL在同一個(gè)服務(wù)器上,Java代碼打印時(shí)間出來都是對(duì)的,結(jié)果一插入數(shù)據(jù)庫(kù)時(shí)間就錯(cuò)了。
然后進(jìn)入數(shù)據(jù)庫(kù)查看時(shí)間和時(shí)區(qū):
mysql> select curtime(); mysql> show variables like '%time_zone%';
發(fā)現(xiàn)時(shí)間也沒問題,都是北京時(shí)間,那為什么通過JDBC一插就差那么十幾個(gè)小時(shí)呢?
問題的原因在這里:一次 JDBC 與 MySQL 因 “CST” 時(shí)區(qū)協(xié)商誤解導(dǎo)致時(shí)間差了 14 或 13 小時(shí)的排錯(cuò)經(jīng)歷
解決辦法:
手動(dòng)修改MySQL的時(shí)區(qū),明確指定:
mysql> set global time_zone='+08:00'; mysql> set time_zone='+08:00'; mysql> flush privileges;
或者修改my.cnf配置文件,一勞永逸,添加:
[mysqld] default-time-zone = '+08:00'
即可,最后記得重啟MySQL服務(wù),最好還能重啟一下Tomcat。
到此這篇關(guān)于MYSQL時(shí)區(qū)導(dǎo)致時(shí)間差了14或13小時(shí)的解決方法的文章就介紹到這了,更多相關(guān)MYSQL差14或13小時(shí)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于MySQL數(shù)據(jù)庫(kù)復(fù)制Master-Slave架構(gòu)的分析
本篇文章是對(duì)MySQL數(shù)據(jù)庫(kù)復(fù)制Master-Slave架構(gòu)進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06
Mysql數(shù)據(jù)庫(kù)介紹及mysql顯示命令
這篇文章主要介紹了Mysql數(shù)據(jù)庫(kù)介紹及mysql顯示命令 的相關(guān)資料,需要的朋友可以參考下2016-04-04
mysql數(shù)據(jù)庫(kù)隔離級(jí)別詳解
SQL標(biāo)準(zhǔn)定義了4類隔離級(jí)別,包括了一些具體規(guī)則,用來限定事務(wù)內(nèi)外的哪些改變是可見的,哪些是不可見的,下面這篇文章主要給大家介紹了關(guān)于mysql數(shù)據(jù)庫(kù)隔離級(jí)別的相關(guān)資料,需要的朋友可以參考下2022-06-06
mysql報(bào)錯(cuò)RSA?private?key?file?not?found的解決方法
當(dāng)MySQL報(bào)錯(cuò)RSA?private?key?file?not?found時(shí),可能是由于MySQL的RSA私鑰文件丟失或者損壞導(dǎo)致的,此時(shí)可以重新生成RSA私鑰文件,以解決這個(gè)問題2023-06-06
在MySQL中使用子查詢和標(biāo)量子查詢的基本操作教程
這篇文章主要介紹了在MySQL中使用子查詢和標(biāo)量子查詢的基本操作教程,子查詢的使用時(shí)MySQL入門學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-12-12

