time_zone timestamp datetime in MySQL

Posted by Vincent on July 15, 2014

MySQL上的time_zone时区设置对timestamp和datetime有什么样的影响,是否一样。

先将系统时间改成美国洛杉矶时间
[cc lang='sql']
cp /usr/share/zoneinfo/America/Los_Angeles /etc/localtime

$date
Mon Jul 14 23:47:30 PDT 2014

root@(none) 11:49:44>show variables like '%time_zone%';
+------------------+--------+
| Variable_name | Value |
+------------------+--------+
| system_time_zone | PDT |
| time_zone | SYSTEM |
+------------------+--------+
[/cc]

创建一个有datetime和timestamp字段的表
[cc lang='sql'] CREATE TABLE `xf_time` (
`id` int(11) NOT NULL DEFAULT '0',
`gmt_c` datetime DEFAULT NULL,
`gmt_m` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

root@test 11:52:54>insert into xf_time values(1,now(),now());
Query OK, 1 row affected (0.00 sec)

root@test 11:54:30>select * from xf_time;
+----+---------------------+---------------------+
| id | gmt_c | gmt_m |
+----+---------------------+---------------------+
| 1 | 2014-07-14 23:54:30 | 2014-07-14 23:54:30 |
+----+---------------------+---------------------+
1 row in set (0.00 sec)[/cc]

更改MySQL的time_zone到北京时间所在东八区
[cc lang='sql']root@test 11:54:35>set time_zone = '+8:00';
Query OK, 0 rows affected (0.00 sec)
root@(none) 12:03:04>show variables like '%time_zone%';
+------------------+--------+
| Variable_name | Value |
+------------------+--------+
| system_time_zone | PDT |
| time_zone | +08:00 |
+------------------+--------+
2 rows in set (0.00 sec)[/cc]

可以看到MySQL的time_zone已经改变,而且当前时间都已经发生变化。

[cc lang='sql']root@test 12:00:58>select now();
+---------------------+
| now() |
+---------------------+
| 2014-07-15 15:01:01 |
+---------------------+
1 row in set (0.00 sec)

root@test 12:01:01>select * from xf_time;
+----+---------------------+---------------------+
| id | gmt_c | gmt_m |
+----+---------------------+---------------------+
| 1 | 2014-07-14 23:54:30 | 2014-07-15 14:54:30 |
+----+---------------------+---------------------+
1 row in set (0.00 sec)[/cc]

datetime类型字段在time_zone发生变化后,没有变化。但timestamp类型是跟随时区发生了变化。故dateime类型跟时区无关,timestamp类型跟时区密切相关
所以说:
MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME.)

小结:更改MySQL时区的方式有
1. 调整系统OS时区 cp /usr/share/zoneinfo/America/Los_Angeles /etc/localtime 将相应的时区文件覆盖
2. 调整MySQL的启动参数文件: 在[mysqld]下面加上 default-time-zone=timezone 比如 default-time-zone='+8:00' 。 通过登录后的set time-zone 是session级别的,不能做为全局使用,但也有其使用的场景

--eof


This work is licensed under a CC A-S 4.0 International License.