Timezones in PHP.

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.
    $unix_time = strtotime($timestamp);
    // Unix time is seconds since the epoch (in UTC).

    // Express the Unix time as a string for timezone $tz.
    $result = strftime("%Y-%m-%d %H:%M %Z",$unix_time);
    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');


British winter time is the same as UTC.

tztotz("2006-12-01 12:00","Europe/London","UTC")
      --> 2006-12-01 12:00 UTC

British summer time is UTC+0100.

tztotz("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.

Comment · Comments Feed · TrackBack

  1. Giles said,

    12 March, 2007 @ 18:40

    It would probably be an improvement to clean it up with a couple of helper functions – since the PHP documentation indicates that the 5.1.x functions offer more functionality than the getenv() option. Then at least 5.1.x users have the advantage of the built-in functionality.

    function custom_timezone_set( $tz )
        if (function_exists('date_default_timezone_set')) {
            date_default_timezone_set( $tz );
        else {
    function custom_timezone_get()
        if (function_exists('date_default_timezone_get')) {
        else {
  2. Mark Pennington said,

    21 April, 2009 @ 14:11

    Thanks for this, really useful peice of script!

  3. Ryan said,

    9 September, 2010 @ 18:42

    Thank you~

  4. ausbildung zum hundetrainer nrw said,

    4 October, 2012 @ 06:32

    Wow! Thank you! I constantly wanted to write on my site something like that.

    Can I take a portion of your post to my website?

Leave a Comment