i was trying to compare the difference between 2 dates, but it seems the results are pretty wrong, for example this code:
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days')."<br />";
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-15');
$interval2 = $datetime1->diff($datetime2);
echo $interval2->format('%R%a days')."<br />";
if($interval == $interval2){ echo "true"; }else{echo "false"; }
Returns true, but above you can see the date differences are not the same, in fact echo prints +2 and +4. Any idea in how to compare 2 date differences?
EDIT: the datetime::diff returns a dateinterval object, in fact it doesn’t implement comparison operators, https://bugs.php.net/bug.php?id=49914
I’ll use dateinterval vars to check the difference, thanks for the answers
It seems that DateInterval doesn’t implement a comparison function internally. Extensions are allowed to define custom comparison rules for their predefined classes. Evidently it falls back to a loose comparison that the objects are of the same class.
This feature request provides a patch to add this functionality in, but it doesn’t seem to have made it into the source at any point.
To get around this issue, you can either compare each member variable of your objects yourself (years, months etc.) or you can cast each object to an array: