0

如果您从 PHP 列表中获得时区标识符,那么将给定的 GMT 日期转换为本地时间非常容易:http ://www.php.net/manual/en/timezones.php

例如,您可以这样做(其中 $fromTimeZone 只是 'GMT',$toTimeZone 只是该列表中的常量之一(即 'America/Chicago'),而 $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() 类型的函数都基于服务器的时区。我似乎无法让它忽略它并使用明确给出的时区偏移量。

4

1 回答 1

0

您可以将特定偏移量转换为 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使用不同的时区构造,则日期/时间将转换为指定的时区。

于 2012-04-20T23:20:32.527 回答