Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Difference in months between two dates? [duplicate]

Tags:

php

datediff

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?

like image 334
Jaiff Avatar asked May 03 '12 08:05

Jaiff


People also ask

How can I get the number of months between two dates in PHP?

php $sdate = "1981-11-04"; $edate = "2013-09-04"; $date_diff = abs(strtotime($edate) - strtotime($sdate)); $years = floor($date_diff / (365*60*60*24)); $months = floor(($date_diff - $years * 365*60*60*24) / (30*60*60*24)); $days = floor(($date_diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24)); printf("%d ...

How can I get the difference between two dates in PHP?

To calculate the difference between two dates in PHP, call date_diff() date/time function, and pass the two dates as argument to it. date_diff() function returns a DateInterval object, or FALSE if calculating the difference is not successful.

Which of the following operators is appropriate to find the difference between 2 dates?

*You may also use the DATEDIFF function. COMPUTE days2 = DATEDIFF(date2,date1,"days"). EXE.

Which date function is used to find the difference between two dates in SQL?

SQL Server DATEDIFF() Function The DATEDIFF() function returns the difference between two dates.


Video Answer


2 Answers

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');
like image 112
Boby Avatar answered Sep 20 '22 16:09

Boby


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');
?>
like image 35
Devator Avatar answered Sep 19 '22 16:09

Devator