A neat way to change PHP / MySQL timezones at the script level

If you do any programming on shared hosting environments – like MediaTemple, Go Daddy or whatever – you’ll be familiar with the problem of timezones. While it’s easy to set the correct timezone on a server you have full control over, things get much trickier on a shared server.

However, if you’re working on PHP and MySQL there is a quick, neat fix you can apply to any scripts that rely on the system clock.

// The PHP fix…
date_default_timezone_set(‘Europe/London’);
// The MySQL fix…
mysql_query(“SET `time_zone` = ‘”.date(‘P’).”‘”);

This works because PHP understands the correct offset for named timezones (master list here) and can then pass the timezone offset (in the correct “+02:00” format) to MySQL via the ‘P’ date parameter.

So, in summary… once you’ve opened the mysql connection in your PHP script, just add these two lines:

date_default_timezone_set(‘Europe/London’);
mysql_query(“SET `time_zone` = ‘”.date(‘P’).”‘”);

And that’s about it.