与 MySQL 因“CST” 时区协商误解导致时间差了13 小时

CST 时区
名为 CST 的时区是一个很混乱的时区,有四种含义:

  • 美国中部时间 Central Standard Time (USA) UTC-05:00 / UTC-06:00
  • 澳大利亚中部时间 Central Standard Time (Australia) UTC+09:30
  • 中国标准时 China Standard Time UTC+08:00
  • 古巴标准时 Cuba Standard Time UTC-04:00

美国从“3月11日”至“11月7日”实行夏令时,美国中部时间改为 UTC-05:00,与 UTC+08:00 相差 13 小时。

 

背景:偶然一次,发现从数据库读出的时间打印出来比实际时间多了13小时。
检查数据库时区:

而数据库连接没有定义具体时区:

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&useSSL=true&allowMultiQueries=true

 

分析原因

mybatis 在与 MySQL 协商会话时区时,mybatis 根据查询数据库时区,获取到 CST ,认为数据库时区是美国中部时间 UTC-05:00,而当前系统时区是 UTC+08:00,所以在拿到数据库的时间上面加了13个小时。导致最后时间比实际多。

 

解决办法

1:修改数据库时区为 UTC+08:00,不用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] 节下增加 default-time-zone = '+08:00'。

2:与数据库连接时,定义时区,避免mybatis框架从mysql获取时区。在连接上加上  serverTimezone=GMT%2B8

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&useSSL=true&allowMultiQueries=true&serverTimezone=GMT%2B8

 

环境:

  MySQL5.7.12

  SpringBoot  2.0.1.RELEASE

  MyBatis  3.4.1

 

 如有错误的地方,请指出。谢谢评论。

参考:

https://blog.csdn.net/crystalqy/article/details/90896673

https://juejin.im/post/5902e087da2f60005df05c3d

posted @ 2019-07-05 15:14  MlAlwaysCode  阅读(6144)  评论(0编辑  收藏  举报