Jun
3

PHP: Change UTC time to local time

Did you know that you can quickly change UTC time stamps to Local time by doing the following:

//make sure your time is set
date_default_timezone_set('America/New_York');

$datetime = '2004-02-12T15:19:21+00:00';

//convert the given datetime string to time
$newDatetime = strtotime($datetime);

//re-contruct to format
$newDatetime = date('Y-m-d H:i:s', newDatetime);

It’s so obvious, but I only wished, I knew this before trying all sort of crazy stuff.

5 Comments to “PHP: Change UTC time to local time”

  • […] Originally posted here: PHP Blog on: PHP: Change UTC time to local time […]

  • Julian – HI my blog is showing UTC time and I want west coast pacific time and I am lost. Do I add that code to .htaccess? Thanks for any help.

    • I'm assuming your blog is in php. You can add
      date_default_timezone_set('America/Los_Angeles');
      of the main dispatcher. Usually index.php will do

  • Be aware that the strtotime functions has some limitations, especially on 32bit systems where the max datetime it will grok is from Fri, 13 Dec 1901 20:45:54 UTC to Tue, 19 Jan 2038 03:14:07 UTC.

    This function does a better job if you are looking for dates outside this range:

    function utc_to_local($format_string, $utc_datetime, $time_zone)
    {
    $date = new DateTime($utc_datetime, new DateTimeZone('UTC'));
    $date->setTimeZone(new DateTimeZone($time_zone));
    return $date->format($format_string);
    }

    The call:
    echo utc_to_local('M j Y g:i:s a T','2040-1-12 08:15:30','America/New_York');
    yields:
    Jan 12 2040 3:15:30 am EST

    Hope this helps!

  • Magnificent site. Lots of helpful information here.

    I’m sending it to a few buddies ans also sharing in delicious.
    And certainly, thanks in your sweat!

Leave a comment