Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does datetime->days always returns a positive number

Tags:

php

datetime

// 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?

like image 942
JonoB Avatar asked Mar 14 '13 22:03

JonoB


1 Answers

You could use DateInterval::format.

return $interval->format("%r%a");

Cast to int if needed:

return (int)$interval->format("%r%a");

like image 61
lafor Avatar answered Sep 19 '22 21:09

lafor