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小时。
检查数据库时区:
show variables like "%time_zone%";
而数据库连接没有定义具体时区:
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/index?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)
2.修改数据库连接
jdbc:mysql://localhost:3306/index?useTimezone=true&serverTimezone=GMT%2B8&autoReconnect=true&useUnicode=true&characterEncoding=utf-8&useSSL=true&allowMultiQueries=true