mysql> select now(); +---------------------+ | now() | +---------------------+ | 2020-04-23 17:32:47 | +---------------------+ 1 row in set (0.00 sec)
mysql> show variables like '%time_zone%'; +------------------+--------+ | Variable_name | Value | +------------------+--------+ | system_time_zone | CST | | time_zone | SYSTEM | +------------------+--------+ 2 rows in set (0.00 sec)
发现时间也没问题,都是北京时间。 那么为什么通过mp写进数据库的时间会差那么长时间呢?
因 “CST” 时区协商误解导致时间差了 14 或 13 小时
CST 时区
名为 CST 的时区是一个很混乱的时区,有四种含义:
美国中部时间 Central Standard Time (USA) UTC-06:00
澳大利亚中部时间 Central Standard Time (Australia) UTC+09:30
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()); } } }
// 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 值作为协调时区。
让我们登录到 MySQL 服务器验证这两个值:
1 2 3 4 5 6 7 8
mysql> show variables like '%time_zone%'; +------------------+--------+ | Variable_name | Value | +------------------+--------+ | system_time_zone | CST | | time_zone | SYSTEM | +------------------+--------+ 2 rows in set (0.00 sec)