16

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?

3

2 Answers 2

24

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');
3
  • 51
    This does not work if the interval is more than 12 months. A difference of 13 months will show up as 1. As a user mentioned in a comment on the other answer, you can use $interval->m + 12*$interval->y to fix this.
    – Matthew
    Aug 27, 2015 at 6:26
  • 1
    Why not post a complete answer, or update this one? Oct 9, 2020 at 17:34
  • also, the result of $interval->m + 12*$interval->y will always be positive, you have to check $interval->invert and multiply by -1 or 1 accordingly : ($interval->invert ? -1 : 1) * ($interval->m + (12 * $interval->y)) May 10, 2022 at 12:39
16

Have a look at date_diff:

<?php
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%m months');
?>
8
  • i got error while running this...Fatal error: Call to undefined function date_diff() in C:\test\test.php on line 4
    – Jaiff
    May 3, 2012 at 10:02
  • @Jaiff Which PHP version are you running? 5.3 is required for this function.
    – Devator
    May 3, 2012 at 10:04
  • 2
    My point was, you're not taking into account the year here.
    – Pez Cuckow
    Sep 5, 2013 at 17:16
  • 12
    add in the years with $interval->m + ($interval->y * 12)
    – zzapper
    Jan 15, 2014 at 17:23
  • 1
    Calculate no of months between 2 dates: $date1 = '2017-01-20'; $date2 = '2019-01-20'; $ts1 = strtotime($date1); $ts2 = strtotime($date2); $year1 = date('Y', $ts1); $year2 = date('Y', $ts2); $month1 = date('m', $ts1); $month2 = date('m', $ts2); echo $joining_months = (($year2 - $year1) * 12) + ($month2 - $month1);
    – Kamlesh
    Feb 7, 2019 at 7:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.