方法时区getOffset如何在PHP上使用日期?

时间:2018-01-17 12:38:03

标签: php datetime timezone-offset

我试图了解PHP如何使用给定的日期时间在DateTimeZone对象上返回getOffset结果。据我所知,无论我通过什么日期时间,结果总是一样的。

public function testGetOffset()
{
    // UTC offset is 00:00 (0 seconds)
    $timeZoneUtc = new \DateTimeZone('UTC');
    $dateUTC = new \DateTime('now', $timeZoneUtc);

    // America/Sao_Paulo offset is -02:00 (-7200 seconds)
    $timeZoneSP = new \DateTimeZone('America/Sao_Paulo');
    $dateSP = new \DateTime('now', $timeZoneSP);

    // America/New_York offset is -05:00 (-18000 seconds)
    $timeZoneNY = new \DateTimeZone('America/New_York');
    $dateNY = new \DateTime('now', $timeZoneNY);


    $this->assertEquals(0, $timeZoneUtc->getOffset($dateUTC)); // true
    $this->assertEquals(0, $timeZoneUtc->getOffset($dateNY));  // true
    $this->assertEquals(0, $timeZoneUtc->getOffset($dateSP));  // true


    $this->assertEquals(-7200, $timeZoneSP->getOffset($dateUTC)); // true
    $this->assertEquals(-7200, $timeZoneSP->getOffset($dateNY));  // true
    $this->assertEquals(-7200, $timeZoneSP->getOffset($dateSP));  // true


    $this->assertEquals(-18000, $timeZoneNY->getOffset($dateUTC)); // true
    $this->assertEquals(-18000, $timeZoneNY->getOffset($dateNY));  // true
    $this->assertEquals(-18000, $timeZoneNY->getOffset($dateSP));  // true
}

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:2)

偏移仅在DST转换期间发生变化。纽约将于3月11日从冬季到夏季过渡。getOffset告诉您该时区的偏移是在该特定时间。你所提供的所有时间都是今天,早在DST过渡日期之前,所以它们都会产生相同的偏移量。尝试获取3月11日之前和之后的日期的偏移量以查看差异。

答案 1 :(得分:1)

A date is an absolute moment in time, it doesn't depend on a timezone. The timezone is used only when the date is formatted as string.

Internally, all three DateTime objects created by the code store the same value: the number of seconds (and microseconds on PHP 7) since 1970-01-01 00:00:00 UTC.