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'); 
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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))
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 Comments

i got error while running this...Fatal error: Call to undefined function date_diff() in C:\test\test.php on line 4
@Jaiff Which PHP version are you running? 5.3 is required for this function.
My point was, you're not taking into account the year here.
add in the years with $interval->m + ($interval->y * 12)
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);
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.