Setting the MySQL timezone per connection
Posted December 20th, 2008 in MySql (Updated January 1st, 2009)
There may be instances when you need to set your MySQL database to a different timezone from the one the server is in, but only for a specific website or application. It is possible to set the timezone on a per connection basis with MySQL and this post looks at how to do it.
For example, you might want to set the MySQL timezone to be the same as in Los Angeles. After you have connected to the MySQL database you would issue this query:
SET time_zone = 'America/Los_Angeles';
Any subsequent queries using date and time functions will report the date and time using that timezone instead of the MySQL server default for your system.
A slight catch to the above example is that the named timezones are not set up by default with MySQL and you must set them up yourself. From a Linux system this is trival as long as you are administering the server yourself. If not, you'll need to resort to using UTC offsets instead like in the following example SQL query:
SET time_zone = '-8:00';
If you don't have the timezone names set up, or the timezone name you are trying to use doesn't exists, you'll see an error like so:
#1298 - Unknown or incorrect time zone: 'America/Los_Angeles'
If you do have sufficient rights to the server, you can simply issue a command like this from the command line, assuming your zoneinfo files are at /usr/share/zoneinfo (they are on a CentOS / Red Hat Enterprise Linux setup):
mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql
This will load the timezone names and offsets into the "mysql" database and you can view the names by querying the "time_zone_name" table.
Note that you should run this regularly to rebuild the timezone database because timezone information does change over time. The SQL queries run truncate data from the appropriate tables so each time you run the full set of data is updated and the old records purged.
- MySQL CONVERT_TZ returns null (Wednesday, September 30th 2009)
- How to enable remote access to a MySQL database server (Wednesday, April 1st 2009)
- Changing the timezone with PHP (Wednesday, December 31st 2008)
- Using date_add in MySQL to add intervals to dates (Thursday, September 25th 2008)
- Formatting Dates and Times with MySQL (Saturday, July 17th 2004)
- Delete All Data in a MySQL Table (Friday, July 16th 2004)