Reputation: 85
I can't figure it out why these two datetime objects aren't equal when I compare them:
$x = new \DateTime('2019-10-10', new \DateTimeZone('UTC'));
$x->setTime(10, 10, 10);
$y = new \DateTime('2019-10-10', new \DateTimeZone('Europe/Bucharest'));
$y->setTime(12, 10, 10);
var_dump($x, $y, $x == $y, $x > $y);
Upvotes: 1
Views: 866
Reputation: 7683
DateTime objects with different time zones are considered the same for simple comparison if they represent the same time.
Example:
$dt1 = new DateTime('2019-10-10 00:00', new DateTimeZone('UTC'));
$dt2 = new DateTime('2019-10-10 03:00', new DateTimeZone('Europe/Bucharest'));
var_dump($dt1 == $dt2); //bool(true)
The result of comparison is equal because at the time of 2019-10-10 00:00 it was already 03:00 in Bucharest. The comparisons with larger and smaller work analogously.
Note: DateTime has implemented special comparisons for this and reacts differently than the comparison of "normal objects"
Upvotes: 2
Reputation: 8162
It's different because change the time see result:
object(DateTime)#1 (3) {
["date"]=>
string(26) "2019-10-10 10:10:10.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(3) "UTC"
}
object(DateTime)#2 (3) {
["date"]=>
string(26) "2019-10-10 12:10:10.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(16) "Europe/Bucharest"
}
bool(false)
bool(true)
As you can see 1 is "2019-10-10 10:10:10.000000" and second is "2019-10-10 12:10:10.000000".
If you want compare just date:
$x = new DateTime('2019-10-10', new DateTimeZone('UTC'));
$x->setTime(10, 10, 10);
$y = new DateTime('2019-10-10', new DateTimeZone('Europe/Bucharest'));
$y->setTime(12, 10, 10);
$firstDate = $x->format('Y-m-d');
$secondDate = $y->format('Y-m-d');
var_dump($firstDate, $secondDate, $firstDate == $secondDate, $firstDate > $secondDate);
Output:
string(10) "2019-10-10" string(10) "2019-10-10" bool(true) bool(false)
Upvotes: 1