如果转载,请加上连接https://blog.csdn.net/a544272939/article/details/82864899,万分感谢!
一:CST时区协商误解导致时间相差13或14小时
名为 CST 的时区是一个很混乱的时区,它有四种含义:
- 美国中部时间 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
其中在美国时区,从“3月11日”至“11月7日”实行夏令时,所以美国中部时间改为 UTC-05:00,与 UTC+08:00 相差 13 小时。
排错过程
在项目中,偶然发现数据库中存储的 Timestamp 字段的 unix_timestamp() 值比真实值少了 13 个小时。通过调试追踪,发现了 com.mysql.cj.jdbc
里的时区协商有问题。
当 JDBC 与 MySQL 开始建立连接时,会调用 com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer()
获取服务器参数,其中我们看到调用 this.session.configureTimezone()
函数,它负责配置时区。
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());