Setting the Timezone in PHP – Local Time vs. Server Time

Most website CMS or blogging platforms will take care of the time and date settings for you and you get to select what timezone applies to your website. I call this the PHP local time. This is something that’s necessary when your web server is in a different timezone than your own, which I call PHP server time. If you’re not using a specialized platform to set up your website, it’s helpful to know how to change it on your own.

Changing the Timezone

It doesn’t matter exactly how you change the settings because the code is very short. The first thing you need to do is find out what your local timezone is and you can find it by starting at the List of Supported Timezones that the PHP online manual provides. Now, the lists aren’t completely intuitive and sometimes you need to know the name of the closest city to you. You would think that Honolulu, Hawaii would be shown under the “America” list, but it’s actually under the “Pacific” list. Regardless, using the names as listed is a lot easier than adding or subtracting hours from the server time.

If you need to save the server’s timezone for some reason, you should store it in a unique variable before you change it.

The Code

PHP 5 introduced a way to change the timezone that differs from PHP 4 and I think PHP 3 required manipulating the hours. For the sake of completeness, I’ll show you how to do it in both PHP 4 and PHP 5 even if you shouldn’t be using PHP 4 anymore.

// My timezone
$timezone = "America/Phoenix";

// PHP 5
date_default_timezone_set($timezone);

// PHP 4
putenv ('TZ=' . $timezone);

See, I told you it was short. The one thing you have to remember, because it could trip you up, is that you have to change the timezone before you start using any date or time functions.

If you have access to the php.ini file on your server, it might seem like setting the timezone there would be all you need to do. Once you change it with a PHP script, that setting is overridden, so you shouldn’t rely on it always being correct.

Share this: