PHP时区偏移量不正确

时间:2014-10-22 21:44:04

标签: php datetime time timezone timezone-offset

以下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小时)。为什么?

1 个答案:

答案 0 :(得分:1)

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

  

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

因此,如果服务器时区为Europe/Paris,那么getOffset()将返回7200秒,因为Europe / Paris是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);
}