PHP Difference in months between two dates?

Jaiff picture Jaiff · May 3, 2012 · Viewed 71.6k times · Source

Possible Duplicate:
How to calculate the difference between two dates using PHP?
Date Difference in php?

I have two dates in a variable like

$fdate = "2011-09-01"

$ldate = "2012-06-06"

Now I need the difference in months between them.
For example, the answer should be 10 if you calculate this from month 09 (September) to 06 (June) of next year - you'll get 10 as result.
How can I do this in PHP?

Answer

Boby picture Boby · May 4, 2012

A more elegant solution is to use DateTime and DateInterval.

<?php

// @link http://www.php.net/manual/en/class.datetime.php
$d1 = new DateTime('2011-09-01');
$d2 = new DateTime('2012-06-06');

// @link http://www.php.net/manual/en/class.dateinterval.php
$interval = $d2->diff($d1);

$interval->format('%m months');