Pete_1
Pete_1

Reputation: 1011

Returning number of months between two dates

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.

Upvotes: 0

Views: 495

Answers (1)

ameenulla0007
ameenulla0007

Reputation: 2683

$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

Upvotes: 1

Related Questions