How do I compare two DateTime objects in PHP 5.2.8?
The following seems to confirm that there are comparison operators for the DateTime class:
dev:~# php<?phpdate_default_timezone_set('Europe/London');$d1 = new DateTime('2008-08-03 14:52:10');$d2 = new DateTime('2008-01-03 11:11:10');var_dump($d1 == $d2);var_dump($d1 > $d2);var_dump($d1 < $d2);?>bool(false)bool(true)bool(false)dev:~# php -vPHP 5.2.6-1+lenny3 with Suhosin-Patch 0.9.6.2 (cli) (built: Apr 26 2009 20:09:03)Copyright (c) 1997-2008 The PHP GroupZend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologiesdev:~#
From the official documentation:
As of PHP 5.2.2, DateTime objects can be compared using comparison operators.
$date1 = new DateTime("now");$date2 = new DateTime("tomorrow");var_dump($date1 == $date2); // falsevar_dump($date1 < $date2); // truevar_dump($date1 > $date2); // false
For PHP versions before 5.2.2 (actually for any version), you can use diff.
$datetime1 = new DateTime('2009-10-11'); // 11 October 2013$datetime2 = new DateTime('2009-10-13'); // 13 October 2013$interval = $datetime1->diff($datetime2);echo $interval->format('%R%a days'); // +2 days
You can also compare epoch seconds :
$d1->format('U') < $d2->format('U')
Source : http://laughingmeme.org/2007/02/27/looking-at-php5s-datetime-and-datetimezone/(quite interesting article about DateTime)