您可以使用以下命令更改时区set time_zone
:
mysql> set time_zone='Europe/Helsinki';
mysql> select now();
2012-09-21 16:15:06
mysql> set time_zone='Europe/Paris';
mysql> select now();
2012-09-21 15:15:40
例如,使用它,您可以定义一个返回用户时区当前时间的函数:
create function current_time_in_tz(tz varchar(40)) returns datetime
begin
set @old_tz = @@session.time_zone;
set time_zone=tz;
set @now = now();
set time_zone=@old_tz;
return @now;
end
select id, current_time_in_tz(timezone) from users;
请注意,DATE、TIME 和 DATETIME 值不依赖于时区,因此查询时不会自动调整这些类型的列中的值。TIMESTAMP 值被调整:
mysql> create temporary table tbl (dt datetime, ts timestamp);
mysql> insert into tbl values (now(),now());
mysql> select * from tbl;
+---------------------+---------------------+
| dt | ts |
+---------------------+---------------------+
| 2012-09-21 15:21:56 | 2012-09-21 15:21:56 |
+---------------------+---------------------+
mysql> set time_zone='Europe/Helsinki';
mysql> select * from tbl;
+---------------------+---------------------+
| dt | ts |
+---------------------+---------------------+
| 2012-09-21 15:21:56 | 2012-09-21 16:21:56 |
+---------------------+---------------------+
如果set time_zone
失败并出现此错误:
ERROR 1298 (HY000): Unknown or incorrect time zone: 'Europe/Helsinki'
您需要使用如下命令将时区信息加载到 mysql 中:
mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql
有关更多信息,请参阅http://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html