PHP: Daylight Savings Time Support

The ‘old’ way to support time zones in PHP did not have built-in full time zones support. Each time date(‘I’) flag had to be checked to verify daylight savings time period.

For example, to convert local time to GMT could be done the following way.

// time zone difference in hours
$tz = -5;
 
// local date and time
$local = '2011-03-24 11:00:00';
 
// adjust time zone difference in hours
// using daylight savings time flag and convert to seconds
$diff = ($tz + date('I', strtotime($local))) * 3600;
 
// convert to GMT by subtracting $diff number of seconds
$gmt = date('Y-m-d H:i:s', strtotime($local) - $diff);
 
// the output is 2011-03-24 15:00:00
print $gmt;

However utilizing DateTime class included in PHP 5 makes time zone related operations less stressful.

$local = '2011-03-24 11:00:00';
 
// create and instance of DateTime
// using local date/time and its time zone
$date = new DateTime($local, new DateTimeZone('America/New_York'));
 
// change time zone
$date->setTimezone(new DateTimeZone('GMT'));
 
// the date is already converted to GMT
// so the output is 2011-03-24 15:00:00
print $date->format('Y-m-d H:i:s');

So using time zone name instead of actual difference in hours or seconds allows to take care of daylight savings time automatically.

However unlike MySQL CONVERT_TZ() PHP uses different list of time zone names. For example, for Eastern standard time PHP offers ‘America/New_York’ time zone name while MySQL prefers ‘US/Eastern’.

No Comment

No comments yet

Leave a reply