Are PHP DateInterval comparable like DateTime?

In short, comparing of DateInterval objects is not currently supported by default (as of php 5.6).

As you already know, the DateTime Objects are comparable.

A way to achieve the desired result, is to subtract or add the DateInterval from a DateTime object and compare the two to determine the difference.

Example: https://3v4l.org/kjJPg

$buildDate = new DateTime('2012-02-15');
$releaseDate = clone $buildDate;
$releaseDate->setDate(2012, 2, 14);
$buildDate->add(new DateInterval('P15D'));

var_dump($releaseDate < $buildDate); //bool(true)

Edit

As of the release of PHP 7.1 the results are different than with PHP 5.x, due to the added support for microseconds.

Example: https://3v4l.org/rCigC

$a = new \DateTime;
$b = new \DateTime;

var_dump($a < $b);

Results (7.1+):

bool(true)

Results (5.x – 7.0.x, 7.1.3):

bool(false)

To circumvent this behavior, it is recommended that you use clone to compare the DateTime objects instead.

Example: https://3v4l.org/CSpV8

$a = new \DateTime;
$b = clone $a;
var_dump($a < $b);

Results (5.x – 7.x):

bool(false)

Leave a Comment