3.11. Calculating Time with Time Zones
Problem
You need to calculate times in different time zones. For example, you want to give users information adjusted to their local time, not the local time of your server.
Solution
For simple calculations, you can explicitly add or subtract the offsets between two time zones:
// If local time is EST $time_parts = localtime(); // California (PST) is three hours earlier $california_time_parts = localtime(time() - 3 * 3600);
On Unix-based systems, if you don’t know the offsets
between time zones, just set the TZ
environment
variable to your target time zone:
putenv('TZ=PST8PDT'); $california_time_parts = localtime();
Discussion
Before we sink too deeply into the ins and outs of time zones, we want to pass along the disclaimer that the U.S. Naval Observatory offers at http://tycho.usno.navy.mil/tzones.html. Namely, official worldwide time-zone information is somewhat fragile “because nations are sovereign powers that can and do change their timekeeping systems as they see fit.” So, remembering that we are at the mercy of the vagaries of international relations, here are some ways to cope with Earth’s many time zones.
For a relatively simple treatment of
offsets between time zones, use an array in your program that has the
various time zones’ offsets from
UTC. Once you determine what time zone
your user is in, just add that offset to the appropriate UTC time and
the functions that
print out UTC time (e.g., gmdate( )
, gmstrftime( )
) can print ...
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.