Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - comparing datetime objects with different timezone

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);
like image 630
LDev Avatar asked Feb 20 '26 07:02

LDev


1 Answers

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"

like image 75
jspit Avatar answered Feb 22 '26 20:02

jspit