How do I convert timestamps between UTC (GMT) and an arbitrary timezone in PHP?
These function work on PHP 4 and 5.
/** Converts a timestamp between arbitrary timezones. */
function tz_to_tz($timestamp,$from_tz,$to_tz) {
$old_tz = getenv('TZ');
// Parse $timestamp and extract the Unix time.
if(!empty($from_tz))
putenv("TZ=$from_tz");
$unix_time = strtotime($timestamp);
// Unix time is seconds since the epoch (in UTC).
// Express the Unix time as a string for timezone $tz.
putenv("TZ=$to_tz");
$result = strftime("%Y-%m-%d %H:%M %Z",$unix_time);
putenv("TZ=$old_tz");
return $result;
}
/** Converts a timestamp with timezone information into
* an arbitrary timezone. */
function to_tz($timestamp_with_timezone,$to_tz) {
// Set $from_tz to blank, so that $timestamp_with_timezone
// is parsed to determine timezone.
return tz_to_tz($timestamp_with_timezone,'',$to_tz);
}
/** Converts a timestamp with timezone information into UTC. */
function to_utc($timestamp_with_timezone) {
return to_tz($timestamp_with_timezone,'UTC');
}
Examples
British winter time is the same as UTC.
tz_to_tz("2006-12-01 12:00","Europe/London","UTC")
--> 2006-12-01 12:00 UTC
British summer time is UTC+0100.
tz_to_tz("2006-08-01 12:00","Europe/London","UTC")
--> 2006-08-01 11:00 UTC
There is a cleaner way to do this in PHP 5, using date_default_timezone_set() and date_default_timezone_get() instead of setting the TZ environment variable. I'm sticking to this for the time-being though, since most people who use my stuff still seem to be on PHP 4.
These functions are hereby released into the public domain.
firetree.net