0

Before you call the firing squad, I realize this question has been asked before. I've looked at what seems like 20 examples on stackoveflow (and other places) and am not understanding why my code won't work. I'm simply trying to use PHP's date_diff() function to get the number of months between two dates. I'm coding in procedural style only please.

The example that I see most often:

$startdate = "2013-06-26";
$currentdate = "2014-06-26";

$date1 = date_create($startdate);
$date2 = date_create($currentdate);
$interval = date_diff($date2, $date1);

echo $interval->format("%M months");

This seems to be the common-type answer, procedural wise, and work for everyone but me. Returns "00 Months", no errors. I'm running PHP 4+. I feel like I've made a sincere effort to understand this function and there is just something that I'm not getting. If anyone could shed light on why my code is not working correctly, I would be grateful.

John Conde
  • 217,595
  • 99
  • 455
  • 496
Pete_1
  • 981
  • 3
  • 14
  • 23
  • 1
    That's because the difference is a full year. DateInterval will report from 0 - 11 months before rolling over to one year. If you do: `echo $interval->format("%y years");` it will say 1 to represent the difference. There is no way to have DateInterval report more than 11 months. – John Conde Jun 26 '14 at 20:16
  • Thank you, this is the missing link! – Pete_1 Jun 26 '14 at 20:56

1 Answers1

1
$date1 = new DateTime("2013-06-26");
$date2 = new DateTime("2014-06-26");
$interval = date_diff($date1, $date2);
echo $interval->m + ($interval->y * 12) . ' months';

This would help

ameenulla0007
  • 2,663
  • 1
  • 12
  • 15