PHP比较DateTimeZone对象

时间:2015-06-29 09:05:08

标签: php unit-testing datetime timezone

这是将DateTimeZone对象与给定时区进行比较的唯一方法吗?

    $dateNow = new \DateTime('now');
    $tz = $dateNow->getTimezone();
    $this->assertEquals($tz->getName(), $tz->listIdentifiers(\DateTimeZone::UTC)[0]);

既不比较两个对象也不比较常量。顺便说一句,DateTimeZone常量用于什么?

1 个答案:

答案 0 :(得分:0)

可以通过各自的名称比较两个DateTimeZone对象。

仅使用DateTimeZone对象的示例:

$UTC = new DateTimeZone('UTC');
$UTC2 = new DateTimeZone('UTC');
$PST = new DateTimeZone('America/Los_Angeles');
if ($UTC->getName() == $PST->getName())
{
    echo "UTC equals PST";
}
else
{
    echo "UTC does not equal PST";
}

if ($UTC->getName() == $UTC2->getName())
{
    echo "UTC equals UTC";
}
else
{
    echo "UTC does not equal UTC";
}

使用DateTime对象的示例:

$now_UTC = new DateTime('now');
$now_UTC->setTimezone(new DateTimeZone('UTC'));
$now_PST = new DateTime('now');
$now_PST->setTimezone(new DateTimeZone('America/Los_Angeles'));

if ($now_UTC->getTimezone()->getName() == $now_PST->getTimezone()->getName())
{
    echo "UTC equals PST";
}
else
{
    echo "UTC does not equal PST";
}

$now_PST->setTimezone(new DateTimeZone('UTC'));

if ($now_UTC->getTimezone()->getName() == $now_PST->getTimezone()->getName())
{
    echo "UTC equals UTC";
}
else
{
    echo "UTC does not equal UTC";
}