mysql时区问题总结

1.首先明确一下mysql几个参数的含义


全局参数system_time_zone
系统时区,在MySQL启动时会检查当前系统的时区并根据系统时区设置全局参数system_time_zone的值。

The system time zone. When the server starts, it attempts to determine the time zone of the host machine automatically and uses it to set thesystem_time_zone system variable. The value does not change thereafter.

 

全局参数time_zone

用来设置每个连接会话的时区,默认为system时,使用全局参数system_time_zone的值。

The current time zone. This variable is used to initialize the time zone for each client that connects. By default, the initial value of this is 'SYSTEM' (which means, “use the value of system_time_zone”).

 

参数log_timestamps
用于设置Error Log/Genaral Log/Slow Log这三种日志的时间信息。
有效值为UTC(默认)和SYSTEM(本地系统时区),当设置为system时,会使用参数system_time_zone的值。

 

修改参数time_zone

# 启动命令 --default-time-zone=timezone

# 配置文件 default-time-zone=timezone

# 运行期间 set global time_zone = timezone set global time_zone='+8:00' set global time_zone='Asia/Shanghai'

2. mysql 字段类型区别 TIMESTAMP与DATETIME

相同

显示

TIMESTAMP列的显示格式与DATETIME列相同。换句话说,显示宽度固定在19字符,并且格式为YYYY-MM-DD HH:MM:SS。

 

不同

范围

datetime 以'YYYY-MM-DD HH:MM:SS'格式检索和显示DATETIME值。支持的范围为'1000-01-01 00:00:00'到'9999-12-31 23:59:59'TIMESTAMP值不能早于1970或晚于2037

储存

TIMESTAMP

1.4个字节储存(Time stamp value is stored in 4 bytes)

2.值以UTC格式保存( it stores the number of milliseconds)

3.时区转化 ,存储时对当前的时区进行转换,检索时再转换回当前的时区。

datetime

1.8个字节储存(8 bytes storage)

2.实际格式储存(Just stores what you have stored and retrieves the same thing which you have stored.)

3.与时区无关(It has nothing to deal with the TIMEZONE and Conversion.)

 

实例对比

现在我来做个时区对他们的影响。

1.先插入一个数据insert into `test` values(now(), now());

2.改变客户端时区(东9区,日本时区)。

3.再次查看插入的数据,变化了,timestamp类型的数据 增加了 1个小时

接下来 讨论一些timestamp 的其他的属性

1.null 是否为空

timestamp 默认允许为 “非空”(not null by default), 如果你在定义“ts TIMESTAMP DEFAULT NULL” 是非法的。 可以指定为空 null ,“ts TIMESTAMP NULL" ,这时可以在添加语句改变默认值。

 

ts2 TIMESTAMP NULL DEFAULT 0,
ts3 TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP

 

default (一个表中只能有一个列选择下面其中一种)

 

 
default CURRENT_TIMESTAMP
 default CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMPON UPDATE CURRENT_TIMESTAMPON UPDATE 见上2

 

3 驱动连接参数 serverTimezone=Asia/Shanghai

参数取值范围:
在zoneinfo 文件夹中(此文件夹来自 Linux的/usr/share/zoneinfo),取值如 GMT+8, Asia/Shanghai,Europe/Berlin,Iceland;
冰岛是 0区,另外如有'+的值,由’%2B3代替,因为 URL 中’+代表空格,如:
GMT+8 -> GMT%2B8
我们所在时区可以设置的参数有:
GMT+8,Asia/Shanghai,Asia/Chongqing,Asia/Hong_Kong,Hongkong
说明:
此参数是告诉驱动程序从数据拿到的时间需要转为的时区:
(1) serverTimezor 对数据库在时间的插入和读取上没有任何影响,
影响的只是连接数据库的驱动。 
(2) 在插入时间时,比如插入一个 Java 系统当前时间10:00(东8区 假设该参数是东1区),那么驱动就会将当前时间换成 东1区 传给数据库,数据库会认为这个东1区的时间就是数据所在时区时间存储(如果这个参数与数据库时区不一致可能导致时差)。

(3) 在读取时间时,数据根据数据库时区返回时间,根据这个参数东1区认为返回时间就是东1区,驱动就会将从数据拿到的时间转换为系统时间东八区。

 

posted @ 2021-11-09 18:58  selfim写博客  阅读(438)  评论(0编辑  收藏  举报