Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata