Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Comparing two DateTime objects with different timezones

How does PHP compare DateTime objects when using conditional operators (<, >, >=, <=) ?

Is this comparison timezone invariant?

I tried below code and It looks like it is timezone invariant, can anyone confirm?

Code:

$datestr = "2015-10-09 10:28:01";
$dt = new DateTime($datestr);
$nowdate = new DateTime("now",new DateTimeZone("CET"));
print_r($dt);
echo "<br/>";
print_r($nowdate);
echo "<br/>";
var_dump($nowdate<$dt);

Output:

DateTime Object ( [date] => 2015-10-09 10:28:01 [timezone_type] => 3 [timezone] => Europe/Paris ) 
DateTime Object ( [date] => 2015-10-09 10:53:42 [timezone_type] => 2 [timezone] => CET ) 
boolean false
like image 801
Yogesh Avatar asked Oct 09 '15 10:10

Yogesh


1 Answers

According to the manual:

As of PHP 5.2.2, DateTime objects can be compared using comparison operators.

You've chosen a very confusing example that includes a fixed date that's not clear if it's supposed to be in the past and a time zone that's currently not active (it's CEST here in Western Europe until the end of October). Whatever, I see nothing wrong in your output: 2015-10-09 10:53:42 CET (which equals 2015-10-09 09:53:42 UTC) is clearly greater than 2015-10-09 10:28:01 Europe/Paris (which equals 2015-10-09 08:28:01 UTC).

With a slightly better example we can guess the operands do work as expected:

    echo "Same date:\n";
    $a = new DateTime('2015-01-31 01:23:45 UTC');
    $b = new DateTime('2015-01-31 02:23:45 Europe/Paris');
    var_dump($a, $b, $a<$b, $a==$b, $a>$b);
    echo "\n";

    echo "First greater than second:\n";
    $a = new DateTime('2015-01-31 01:23:46 UTC');
    $b = new DateTime('2015-01-31 02:23:45 Europe/Paris');
    var_dump($a, $b, $a<$b, $a==$b, $a>$b);
    echo "\n";

    echo "First less than second:\n";
    $a = new DateTime('2015-01-31 01:23:45 UTC');
    $b = new DateTime('2015-01-31 02:23:46 Europe/Paris');
    var_dump($a, $b, $a<$b, $a==$b, $a>$b);
Same date:
[...]
bool(false)
bool(true)
bool(false)

First greater than second:
[...]
bool(false)
bool(false)
bool(true)

First less than second:
[...]
bool(true)
bool(false)
bool(false)

Demo with full code.

Another example:

$date_2014 = new DateTime('2014-12-31 23:00:00 -07:00');
$date_2015 = new DateTime('2015-01-01 05:00:00 Asia/Tokyo');
var_dump($date_2014<$date_2015); // bool(false)
like image 66
Álvaro González Avatar answered Nov 09 '22 03:11

Álvaro González