【问题标题】:PHP timezone offset incorrectPHP时区偏移不正确
【发布时间】:2014-10-22 21:44:04
【问题描述】:

以下 PHP 代码:

function serverTimeZone_offset($userTimeZone)
{
    $userDateTimeZone = new DateTimeZone($userTimeZone);
    $userDateTime     = new DateTime("now", $userDateTimeZone);

    $serverTimeZone     = date_default_timezone_get();
    $serverDateTimeZone = new DateTimeZone($serverTimeZone);
    $serverDateTime     = new DateTime("now", $serverDateTimeZone);

    return $serverDateTimeZone->getOffset($userDateTime);
}

function getDefineTimeZone($timezone)
{
    $userDateTimeZone = new DateTimeZone($timezone);
                 return new DateTime("now", $userDateTimeZone);
}

function getServerTimeZone()
{
    $serverTimeZone     = date_default_timezone_get();
    $serverDateTimeZone = new DateTimeZone($serverTimeZone);

    return new DateTime("now", $serverDateTimeZone);
}

$userDateTime   = getDefineTimeZone('America/Curacao');
$serverDateTime = getServerTimeZone();
$timeOffset     = serverTimeZone_offset('America/Curacao');

var_dump($userDateTime);
var_dump($serverDateTime);
var_dump($timeOffset); // the seconds is incorrect ?!?!

// adding the timezone difference
$userDateTime->add(new DateInterval('PT'.$timeOffset.'S'));

var_dump($userDateTime);

将输出:

object(DateTime)[2]
  public 'date' => string '2014-10-22 17:36:39' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'America/Curacao' (length=15)

object(DateTime)[3]
  public 'date' => string '2014-10-22 23:36:39' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/Paris' (length=12)

int 7200

object(DateTime)[2]
  public 'date' => string '2014-10-22 19:36:39' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'America/Curacao' (length=15)

这显然是不正确的。偏移量返回 7200 秒(仅 2 小时)而不是 21600 秒(6 小时)。为什么?

【问题讨论】:

    标签: php datetime time timezone timezone-offset


    【解决方案1】:

    我认为你误解了DateTimeZone::getOffset() 的行为。如DateTimeZone php docs中所说:

    此函数返回在 datetime 参数中指定的日期/时间与 GMT 的偏移量。 使用包含在所使用的 DateTimeZone 对象中的时区信息计算 GMT 偏移量

    所以如果服务器时区是Europe/Paris,那么 getOffset() 将返回 7200 秒,因为欧洲/巴黎是 GMT+01:00,现在是夏令时,所以是 GMT+02:00。

    尝试使用此代码:

    function serverTimeZone_offset($userTimeZone)
    {
        $userDateTimeZone = new DateTimeZone($userTimeZone);
        $userDateTime     = new DateTime("now", $userDateTimeZone);
    
        $serverTimeZone     = date_default_timezone_get();
        $serverDateTimeZone = new DateTimeZone($serverTimeZone);
        $serverDateTime     = new DateTime("now", $serverDateTimeZone);
    
        return $serverDateTimeZone->getOffset($userDateTime) - $userDateTimeZone->getOffset($userDateTime);
    }
    

    【讨论】:

    • 太棒了!我确实完全误解了 getOffset 的行为。感谢您的简化说明。
    猜你喜欢
    • 1970-01-01
    • 2012-03-10
    • 2016-02-26
    • 1970-01-01
    • 2015-07-20
    • 2019-03-08
    • 2013-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多