如果您从 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() 类型的函数都基于服务器的时区。我似乎无法让它忽略它并使用明确给出的时区偏移量。