// Difference from a date in the future: $a = new DateTime('2000-01-01'); $b = new DateTime('2000-01-05'); $interval = $b->diff($a); return $interval->days; // Returns 4 // Difference from a date in the past: $a = new DateTime('2000-01-01'); $b = new DateTime('1999-12-28'); $interval = $a->diff($b); // Arguments swapped return $interval->days; // Returns 4
Why do both of these functions return positive 4? How do I return a negative number if a date is in the past?
You could use DateInterval::format
.
return $interval->format("%r%a");
Cast to int if needed:
return (int)$interval->format("%r%a");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With