2

I've been trying to figure this one out for hours but to no avail: how does one get the difference in full months between two dates, yet accounting for year? The code below

$assignedDate = new DateTime('2011-02-03');
$firstDate = new DateTime('2013-03-03');
$interval = $assignedDate->diff($firstDate);
$months = (int)$interval->format('%m');

Is in the strong belief that the difference between the two is 1, however, this is not applicable for my application and 49 would be the expected result, I've investigated and found this code from this wonderful place but get "Wrong string concatenation operator", so I assumed the problem lay with their stringy output and put (int) ahead of the two, but got 0:

echo (($diff->format('%y') * 12) + $diff->format('%m')) . " full months difference";

Is there a reliable solution to finding the month difference between two dates accounting for the year?

Glavić
  • 42,781
  • 13
  • 77
  • 107
PwnageAtPwn
  • 431
  • 1
  • 6
  • 21
  • What if you tried using a timestamp for them, then using a function to get the differences? Or see this: http://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php?rq=1 – Winter Dec 16 '13 at 17:59

1 Answers1

0

No need to format numbers with format() method. You can simply access public properties on DateInterval object:

$months = $interval->m + $interval->y * 12;

demo

Glavić
  • 42,781
  • 13
  • 77
  • 107
  • Ah yes, very nice. However, if I got behind the assigned date with the first date, it returns a positive number rather than a hoped negative. Is there a way to fix this? – PwnageAtPwn Dec 16 '13 at 19:45
  • @PwnageAtPwn: see public property `invert`, or just format sign with `->format('%R')` (or `'%r'`) method, like [this](https://eval.in/80013). – Glavić Dec 16 '13 at 19:48