PHP timezone handling

Within PHP app, we need to set the timezone to only one timezone – UTC. All timestamp data that going in and out of the database must use UTC timezone so that it’s easier to convert to other timezone value. It’s a basic in PHP script to first set the timezone data

date_default_timezone_set('UTC');

Then it is highly encourage to store all datetime related data in UNIX timestamp, since retrieving it from database is faster than formatted datetime, also easier to format using date() function, and also easy to convert from one timezone to another timezone value, using function below:

timezone_offset_get(new DateTimeZone($timezone), new DateTime()));

$timezone value is one of the timezone identifier listed at List of Supported Timezones at php.net. This function will handle the DST conversion automatically.

To summarize, here’s the correct usage and handling of timezone in PHP

  1. Always set default timezone to UTC, and store user specific timezone info in database or in cookies
  2. Store and retrieve timestamp in UTC timezone
  3. Only convert to local timezone when displaying the timestamp info
// set first early in the script
date_default_timezone_set('UTC');

// data retrieved from database is based on UTC timezone
$timestamp = 1310529794;

// and you're in Los Angeles
$timezone = 'America/Los_Angeles';

// show the formatted datetime for time in L.A
echo date('F j Y, g:i:s a', $timestamp + timezone_offset_get(new DateTimeZone($timezone), new DateTime()));
Share this...
Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInPin on Pinterest

Leave a Reply

Your email address will not be published. Required fields are marked *