start page | rating of books | rating of authors | reviews | copyrights

Book HomePHP CookbookSearch this book

3.13. Accounting for Daylight Saving Time

3.13.1. Problem

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

3.13.2. 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);

3.13.3. 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 Pacific and Eastern time are observing DST, and the calculation is correct again (putting California at seven hours behind UTC).

3.13.4. See Also

Recipe 3.12 for dealing with time zones; documentation on putenv( ) at http://www.php.net/putenv, localtime( ) at http://www.php.net/localtime, gmdate( ) at http://www.php.net/gmdate, and gmstrftime( ) at http://www.php.net/gmstrftime; a detailed presentation on DST is at http://webexhibits.org/daylightsaving/.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.