I am storing dates in a MySQL database in datetime fields in UTC. I'm using PHP, and I've called date_timezone_set('UTC') so that all calls to date() (without timestamp) return the date in UTC.
I then have it so a given web site can select its timezone. Now I want dates to display in the site's timezone. So, if I have a date stored as '2009-04-01 15:36:13', it should display for a user in the PDT timezone (-7 hours) as '2009-04-01 08:36:13'.
What is the easiest (least code) method for doing this via PHP? So far all I've thought of is
date('Y-m-d H:i:s', strtotime($Site->getUTCOffset() . ' hours', strtotime(date($utcDate))));
Is there a shorter way?
What you're doing is the right way of doing things. I'd recommend sticking with working in only UTC and just converting at the last minute for the display.
Here's a quick function I put together for time zone conversion using the DateTime class that comes with PHP. It's a bit more code than you have but I think it's easier and a better way to structure things...
http://richardwillia.ms/blog/2011/04/time-zone-conversion-using-datetime-class/
Hope that helps.
Why not use the built in DateTime/TimeZone functionality?
DateTime Class: http://us3.php.net/manual/en/class.datetime.php DateTimeZone Class: http://us3.php.net/manual/en/class.datetimezone.php
PHP's supported Timezones: http://php.net/manual/en/timezones.php
Here's what we did with our servers. We set everything to use UTC, and we display in the user's time zone by converting from UTC on the fly. The code at the bottom of this post is an example of how to get this to work; you should confirm that it works in all cases with your setup (i.e. daylight savings, etc).
Configuring CentOS
/etc/sysconfig/clock
and setZONE
toUTC
ln -sf /usr/share/zoneinfo/UTC /etc/localtime
Configuring MySQL
Import timezones into MySQL if necessary:
mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql
Edit my.cnf and add the following within the [mysqld] section:
default-time-zone = 'UTC'
PHP Code
This worked for me and it's pretty clean
Having spent a lot of time dealing with this issue, do not attempt to implement time zone translation yourself. It's a royal PIA, fraught with difficulties, and it's very hard to get it right internationally.
That said, the best option is to convert your datetimes in MySQL to timestamps, and just use the database to convert times:
timestamps in MySQL are smaller, and support time zone translation. datetime does not.
Before you display the site information on the page, just invoke the above command, and it will display correctly without any PHP code changes at all.
Caveats:
To turn off timestamp properties:
The DEFAULT 0 disables the column being updated when you update other columns.