UTC Дата / Время Строка в Часовой пояс - PullRequest
55 голосов
/ 21 апреля 2011

Как преобразовать строку даты / времени (например, 2011-01-01 15:00:00), которая является UTC, в любую поддерживаемую php часового пояса, такую ​​как America / New_York или Europe / San_Marino.

Ответы [ 6 ]

131 голосов
/ 21 апреля 2011

PHP DateTime объект довольно гибкий.

$UTC = new DateTimeZone("UTC");
$newTZ = new DateTimeZone("America/New_York");
$date = new DateTime( "2011-01-01 15:00:00", $UTC );
$date->setTimezone( $newTZ );
echo $date->format('Y-m-d H:i:s');
2 голосов
/ 01 октября 2015

Объект PHP DateTime довольно гибкий.

Поскольку пользователь запросил более одного параметра часового пояса, вы можете сделать его универсальным.

Общая функция

function convertDateFromTimezone($date,$timezone,$timezone_to,$format){
 $date = new DateTime($date,new DateTimeZone($timezone));
 $date->setTimezone( new DateTimeZone($timezone_to) );
 return $date->format($format);
}

Использование:

echo  convertDateFromTimezone('2011-04-21 13:14','UTC','America/New_York','Y-m-d H:i:s');

Выход:

2011-04-21 09: 14: 00

1 голос
/ 14 августа 2015
function _settimezone($time,$defaultzone,$newzone)
{
$date = new DateTime($time, new DateTimeZone($defaultzone));
$date->setTimezone(new DateTimeZone($newzone));
$result=$date->format('Y-m-d H:i:s');
return $result;
}

$defaultzone="UTC";
$newzone="America/New_York";
$time="2011-01-01 15:00:00";
$newtime=_settimezone($time,$defaultzone,$newzone);
1 голос
/ 21 апреля 2011

Если предположить, что UTC не включен в строку, то:

date_default_timezone_set('America/New_York');
$datestring = '2011-01-01 15:00:00';  //Pulled in from somewhere
$date = date('Y-m-d H:i:s T',strtotime($datestring . ' UTC'));
echo $date;  //Should get '2011-01-01 10:00:00 EST' or something like that

Или вы можете использовать объект DateTime.

0 голосов
/ 09 декабря 2016

Функция нормализации общего назначения для форматирования любой временной метки из любого часового пояса в другой.Очень полезно для хранения даты и времени пользователей из разных часовых поясов в реляционной базе данных.Для сравнения баз данных сохраните временную метку как UTC и используйте с gmdate('Y-m-d H:i:s')

/**
 * Convert Datetime from any given olsonzone to other.
 * @return datetime in user specified format
 */

function datetimeconv($datetime, $from, $to)
{
    try {
        if ($from['localeFormat'] != 'Y-m-d H:i:s') {
            $datetime = DateTime::createFromFormat($from['localeFormat'], $datetime)->format('Y-m-d H:i:s');
        }
        $datetime = new DateTime($datetime, new DateTimeZone($from['olsonZone']));
        $datetime->setTimeZone(new DateTimeZone($to['olsonZone']));
        return $datetime->format($to['localeFormat']);
    } catch (\Exception $e) {
        return null;
    }
}

Использование:

$from = ['localeFormat' => "d/m/Y H:i A", 'olsonZone' => 'Asia/Calcutta'];

$to = ['localeFormat' => "Y-m-d H:i:s", 'olsonZone' => 'UTC'];

datetimeconv("14/05/1986 10:45 PM", $from, $to); // returns "1986-05-14 17:15:00"
0 голосов
/ 21 апреля 2011

Как насчет:

$timezone = new DateTimeZone('UTC');
$date = new DateTime('2011-04-21 13:14', $timezone);
echo $date->format;
...