简体   繁体   中英

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);

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)

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM