欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

MYSQL時區(qū)導致時間差了14或13小時的解決方法

 更新時間:2023年01月04日 11:09:24   作者:一朵風中搖曳的水仙花  
本文主要介紹了MYSQL時區(qū)導致時間差了14或13小時的解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

p>我一般使用MYSQL定義字段類型時,一般使用TIMESTAMP時間戳來定義創(chuàng)建時間與更新時間,并將其定義為默認值為CURRENT_TIME,但是由于場景特殊,現(xiàn)在我需要將一個任務的開始時間與結束時間記錄,并寫入數(shù)據(jù)庫,那么我的開始時間戳與結束時間戳則不應該是使用數(shù)據(jù)庫自帶的默認值的,而是應該使用我使用java代碼里面?zhèn)鬟M去的LocalDateTime.now()方法。但是插入后數(shù)據(jù)我發(fā)現(xiàn)有問題,插入的時間比我當前的實際時間少13個小時。于是我開始百度找到答案。

名為 CST 的時區(qū)是一個很混亂的時區(qū),在與 MySQL 協(xié)商會話時區(qū)時,Java 會誤以為是 CST -0500,而非 CST +0800。

CST 時區(qū)

名為 CST 的時區(qū)是一個很混亂的時區(qū),有四種含義:

  • 美國中部時間 Central Standard Time (USA) UTC-06:00
  • 澳大利亞中部時間 Central Standard Time (Australia) UTC+09:30
  • 中國標準時 China Standard Time UTC+08:00
  • 古巴標準時 Cuba Standard Time UTC-04:00

今天是“4月28日”。為什么提到日期?因為美國從“3月11日”至“11月7日”實行夏令時,美國中部時間改為 UTC-05:00,與 UTC+08:00 相差 13 小時。

排錯過程

在項目中,偶然發(fā)現(xiàn)數(shù)據(jù)庫中存儲的 Timestamp 字段的 unix_timestamp() 值比真實值少了 13 個小時。通過調試追蹤,發(fā)現(xiàn)了 com.mysql.cj.jdbc 里的時區(qū)協(xié)商有問題。

當 JDBC 與 MySQL 開始建立連接時,會調用 com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer() 獲取服務器參數(shù),其中我們看到調用 this.session.configureTimezone() 函數(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;
}復制代碼

追蹤代碼可知,當 MySQL 的 time_zone 值為 SYSTEM 時,會取 system_time_zone 值作為協(xié)調時區(qū)。

讓我們登錄到 MySQL 服務器驗證這兩個值:

mysql> show variables like '%time_zone%';
+------------------+--------+
| Variable_name    | Value  |
+------------------+--------+
| system_time_zone | CST    |
| time_zone        | SYSTEM |
+------------------+--------+
2 rows in set (0.00 sec)復制代碼

重點在這里!若 String configuredTimeZoneOnServer 得到的是 CST 那么 Java 會誤以為這是 CST -0500,因此 TimeZone.getTimeZone(canonicalTimezone) 會給出錯誤的時區(qū)信息。

debug variables

如圖所示,本機默認時區(qū)是 Asia/Shanghai +0800,誤認為服務器時區(qū)為 CST -0500,實際上服務器是 CST +0800

我們會想到,即便時區(qū)有誤解,如果 Timestamp 是以 long 表示的時間戳傳輸,也不會出現(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() 得到的是剛才那個 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 被轉換為會話時區(qū)的時間字符串了。問題到此已然明晰:

  • JDBC 誤認為會話時區(qū)在 CST-5
  • JBDC 把 Timestamp+0 轉為 CST-5 的 String-5
  • MySQL 認為會話時區(qū)在 CST+8,將 String-5 轉為 Timestamp-13

最終結果相差 13 個小時!如果處在冬令時還會相差 14 個小時!

解決方案

解決辦法也很簡單,明確指定 MySQL 數(shù)據(jù)庫的時區(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)復制代碼

或者修改 my.cnf 文件,在 [mysqld] 節(jié)下增加 default-time-zone = '+08:00'。

修改時區(qū)操作影響深遠,需要重啟 MySQL 服務器,建議在維護時間進行。

JSR-310相關規(guī)范在這個版本就已經支持了,所以大家只要不小于此版本的就放心用吧。舉個例子:

public class User {
    private LocalDateTime createTime;
    // setter ... getter ... 省略了哈
}
 
public interface UserDao {
    @Insert("INSERT INTO user(create_time) values(#{createTime})")
    int insertUser(User user);
}
 
// 在set時間時,一般直接用now方法就好
user.setCreateTime(LocalDateTime.now());

這樣就OK了,如果你數(shù)據(jù)庫表存的是datetime類型的話,MyBatis自動幫你解析轉換,你不用做額外工作。
注意:
這里LocalDateTime默認是不包含時區(qū)信息的,會取當前機器時間的時區(qū),其實一般情況下,是沒有問題的,我用阿里云的服務器(在深圳),直接打印出來就是:

System.out.println(LocalDateTime.now());
// 輸出的是北京時間
2019-03-15T16:51:37.121

當然這樣可能你不是很放心,那么就指明時區(qū):

System.out.println(LocalDateTime.now(ZoneId.of("+08:00")));

MySQL時區(qū)有問題(相差13或14小時)

這個問題最開始讓我非常頭疼,明明我的Tomcat和MySQL在同一個服務器上,Java代碼打印時間出來都是對的,結果一插入數(shù)據(jù)庫時間就錯了。
然后進入數(shù)據(jù)庫查看時間和時區(qū):

mysql> select curtime();
mysql> show variables like '%time_zone%';

發(fā)現(xiàn)時間也沒問題,都是北京時間,那為什么通過JDBC一插就差那么十幾個小時呢?
問題的原因在這里:一次 JDBC 與 MySQL 因 “CST” 時區(qū)協(xié)商誤解導致時間差了 14 或 13 小時的排錯經歷
解決辦法:
手動修改MySQL的時區(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服務,最好還能重啟一下Tomcat。

到此這篇關于MYSQL時區(qū)導致時間差了14或13小時的解決方法的文章就介紹到這了,更多相關MYSQL差14或13小時內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論