Monday, August 24, 2015

How to set time zone of mysql?


on one server,when I run:
mysql> select now();
+---------------------+
| now()               |
+---------------------+
| 2009-05-30 16:54:29 | 
+---------------------+
1 row in set (0.00 sec)
on another server:
mysql> select now();
+---------------------+
| now()               |
+---------------------+
| 2009-05-30 20:01:43 | 
+---------------------+
1 row in set (0.00 sec)
shareimprove this question


8 Answers

I thought this might be useful

There are 3 places where the timezone might be set in MySQL:

in the file "my.cnf" in the [mysqld] section

default_time_zone='+00:00'

@@global.time_zone variable

To see what value they are set to
SELECT @@global.time_zone;
To set a value for it use either one:
SET GLOBAL time_zone = '+8:00';
SET GLOBAL time_zone = 'Europe/Helsinki';
SET @@global.time_zone='+00:00';

@@session.time_zone variable

SELECT @@session.time_zone;
To set it use either one:
SET time_zone = 'Europe/Helsinki';
SET time_zone = "+00:00";
SET @@session.time_zone = "+00:00";
both might return SYSTEM which means that they use the timezone set in my.cnf. For timezone names to work you must setup your timezone information tables need to be populated:http://dev.mysql.com/doc/refman/5.1/en/time-zone-support.html

To get the current timezone

SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP);
It will return 02:00:00 if your timezone is +2:00.

To get the current UNIX timestamp:

SELECT UNIX_TIMESTAMP();
SELECT UNIX_TIMESTAMP(NOW());

To get the timestamp column as a UNIX timestamp

SELECT UNIX_TIMESTAMP(`timestamp`) FROM `table_name`

To get a UTC datetime column as a UNIX timestamp

SELECT UNIX_TIMESTAMP(CONVERT_TZ(`utc_datetime`, '+00:00', @@session.time_zone)) FROM `table_name`
Note: Changing the timezone will not change the stored datetime or timestamp, but it will show select a different datetime from timestamp columns
I made a cheatsheet here: Should MySQL have its timezone set to UTC?

No comments: