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

<![CDATA[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…
// 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:

mysql_query(“SET `time_zone` = ‘”.date(‘P’).”‘”);

And that’s about it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.