Wordpress - Converting timestamps to local time with date_l18n()

I know I'm three months late, but the function you want here is WordPress' get_date_from_gmt().

The function accepts a GMT/UTC date in Y-m-d H:i:s format as the first parameter, and your desired date format as the second parameter. It'll convert your date to the local timezone as set on the Settings screen.

Example usage:

echo get_date_from_gmt( date( 'Y-m-d H:i:s', $my_unix_timestamp ), 'F j, Y H:i:s' );


From the codex:

current_time('timestamp') should be used in lieu of time() to return the blog's local time. In WordPress, PHP's time() will always return UTC and is the same as calling current_time('timestamp', true).

Try this:

define( 'MY_TIMEZONE', (get_option( 'timezone_string' ) ? get_option( 'timezone_string' ) : date_default_timezone_get() ) );
date_default_timezone_set( MY_TIMEZONE );
echo date_i18n('F d, Y H:i', 1365194723);

This sets the default PHP date to WP's timezone_string option, if available, for the duration of the script.


date_i18n($format, $timestamp) formats according to the locale, but not the timezone. get_date_from_gmt($datestring, $format) formats according to the timezone, but not the locale. To get formatting according to both the timezone and the locale, I am doing the following:

function local_date_i18n($format, $timestamp) {
    $timezone_str = get_option('timezone_string') ?: 'UTC';
    $timezone = new \DateTimeZone($timezone_str);

    // The date in the local timezone.
    $date = new \DateTime(null, $timezone);
    $date->setTimestamp($timestamp);
    $date_str = $date->format('Y-m-d H:i:s');

    // Pretend the local date is UTC to get the timestamp
    // to pass to date_i18n().
    $utc_timezone = new \DateTimeZone('UTC');
    $utc_date = new \DateTime($date_str, $utc_timezone);
    $timestamp = $utc_date->getTimestamp();

    return date_i18n($format, $timestamp, true);
}

Example program:

$format = 'F d, Y H:i';
$timestamp = 1365186960;
$local = local_date_i18n($format, $timestamp);
$gmt = date_i18n($format, $timestamp);
echo "Local: ", $local, " UTC: ", $gmt;

Output for the timezone of Los Angeles:

Local: April 05, 2013 11:36 UTC: April 05, 2013 18:36

References:

  • DateTimeZone docs in php.net
  • DateTime docs in php.net, including setTimestamp, getTimestamp and format
  • WordPress' date_i18n docs