使用时区偏移量(而不是时区标识符)将 GMT 时间转换为本地时间


Converting GMT time to local time using timezone offset, not timezone identifier

如果在PHP中为您提供此列表中的时区标识符,则很容易将给定的GMT日期转换为本地时间:http://www.php.net/manual/en/timezones.php

例如,您可以这样做(其中$fromTimeZone只是"GMT",$toTimeZone只是该列表中的常量之一(即"美国/芝加哥"),$datetime是GMT日期):

public static function convertToTimezone($datetime, $fromTimeZone, $toTimeZone, $format = 'Y-m-d H:i')
{
    // Construct a new DateTime object from the given time, set in the original timezone
    $convertedDateTime = new DateTime($datetime, timezone_open($fromTimeZone));
    // Convert the published date to the new timezone
    $convertedDateTime->setTimezone(timezone_open($toTimeZone));
    // Return the udpated date in the format given
    return $convertedDateTime->format($format);
}

但是,如果只给定时区偏移量,我将相同的 GMT 日期转换为本地时间时遇到问题。例如,我没有得到"美国/芝加哥",而是给了-0500(这是该时区的等效偏移量)。

我已经尝试了以下方法(其中$datetime是我的GMT日期,$toTimeZone是偏移量(在本例中为-0500)):

date($format, strtotime($datetime . ' ' . $toTimeZone))

我知道所有 date() 类型的函数都基于服务器的时区。我似乎无法让它忽略这一点并使用明确给出的时区偏移量。

您可以将特定偏移量转换为 DateTimeZone:

$offset = '-0500';
$isDST = 1; // Daylight Saving 1 - on, 0 - off
$timezoneName = timezone_name_from_abbr('', intval($offset, 10) * 36, $isDST);
$timezone = new DateTimeZone($timezoneName);

然后你可以在 DateTime 构造函数中使用它,例如

$datetime = new DateTime('2012-04-21 01:13:30', $timezone);

或与二传手一起:

$datetime->setTimezone($timezone);

在后一种情况下,如果$datetime是使用不同的时区构造的,则日期/时间将转换为指定的时区。