3.12. Accounting for Daylight Saving Time

Problem

You need to make sure your time calculations properly consider DST.

Solution

The zoneinfo library calculates the effects of DST properly. If you are using a Unix-based system, take advantage of zoneinfo with putenv( ):

putenv('TZ=MST7MDT');
print strftime('%c');

If you can’t use zoneinfo, you can modify hardcoded time-zone offsets based on whether the local time zone is currently observing DST. Use localtime( ) to determine the current DST observance status:

// Find the current UTC time 
$now = time();

// California is 8 hours behind UTC
$now -= 8 * 3600;

// Is it DST? 
$ar = localtime($now,true);
if ($ar['tm_isdst']) { $now += 3600; }

// Use gmdate() or gmstrftime() to print California-appropriate time
print gmstrftime('%c',$now);

Discussion

Altering an epoch timestamp by the amount of a time zone’s offset from UTC and then using gmdate( ) or gmstrftime( ) to print out time zone-appropriate functions is flexible — it works from any time zone — but the DST calculations are slightly inaccurate. For the brief intervals when the server’s DST status is different from the target time zone’s, the results are incorrect. For example, at 3:30 A.M. EDT on the first Sunday in April (after the switch to DST), it’s still before the switch (11:30 P.M.) in the Pacific time zone. A server in Eastern time using this method calculates California time to be seven hours behind UTC, whereas it’s actually eight hours. At 6:00 A.M. EDT (3:00 A.M. PDT), both ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.