PHP Compare DateTimeZone Objects

Is this the only way to compare a DateTimeZone object with a given time zone?

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

      

No comparison of two objects, no comparison of constants is performed. By the way, what are the DateTimeZone constants used for?

+3


source to share


1 answer


The two DateTimeZone objects can be compared by their names.

An example using only DateTimeZone objects:

$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";
}

      



An example of using DateTime objects:

$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";
}

      

0


source







All Articles