0

I want to get the total of months between two dates. My code is returning 0 rather than 10 * 12 . Why isn't it working and how do I fix it?

Code:

$date1 = new DateTime("2015-02-14");
$date2 = new DateTime("2025-02-14");
var_dump($date1->diff($date2)->m); // output 0
Jack
  • 16,276
  • 55
  • 159
  • 284
  • possible duplicate of [Calculate months between two dates using DateInterval without wrapping within a year](http://stackoverflow.com/questions/15362664/calculate-months-between-two-dates-using-dateinterval-without-wrapping-within-a) – Merlyn Morgan-Graham Feb 14 '15 at 05:27

2 Answers2

2

Try this way

$date1 = new DateTime("2015-02-14");
$date2 = new DateTime("2025-02-14");
$diff = $date1->diff($date2);

echo (($diff->format('%y') * 12) + $diff->format('%m')) . "months difference";
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
0

Please try this

$date1 = '2015-02-14';
$date2 = '2025-02-14';
$ts1 = strtotime($date1);
$ts2 = strtotime($date2);
$year1 = date('Y', $ts1);
$year2 = date('Y', $ts2);

$month1 = date('m', $ts1); 
$month2 = date('m', $ts2);

$diff = (($year2 - $year1) * 12) + ($month2 - $month1);

Or Else Try this

$d1 = new DateTime("2015-02-14");
$d2 = new DateTime("2025-02-14");
var_dump($d1->diff($d2)->m); // int(4)
var_dump($d1->diff($d2)->m + ($d1->diff($d2)->y*12)); // int(8)
Arun
  • 750
  • 5
  • 12