Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Month difference in php? [duplicate]

Tags:

date

php

datetime

Is there any way to find the month difference in PHP? I have the input of from-date 2003-10-17 and to-date 2004-03-24. I need to find how many months there are within these two days. Say if 6 months, I need the output in months only. Thanks for guiding me for day difference.

I find the solution through MySQL but I need it in PHP. Anyone help me, Thanks in advance.

like image 541
Karthik Avatar asked Apr 21 '10 09:04

Karthik


3 Answers

The easiest way without reinventing the wheel. This'll give you the full months difference. I.e. the below two dates are almost 76 months apart, but the result is 75 months.

date_default_timezone_set('Asia/Tokyo');  // you are required to set a timezone

$date1 = new DateTime('2009-08-12');
$date2 = new DateTime('2003-04-14');

$diff = $date1->diff($date2);

echo (($diff->format('%y') * 12) + $diff->format('%m')) . " full months difference";
like image 130
deceze Avatar answered Oct 12 '22 12:10

deceze


After testing tons of solutions, putting all in a unit test, this is what I come out with:

/**
 * Calculate the difference in months between two dates (v1 / 18.11.2013)
 *
 * @param \DateTime $date1
 * @param \DateTime $date2
 * @return int
 */
public static function diffInMonths(\DateTime $date1, \DateTime $date2)
{
    $diff =  $date1->diff($date2);

    $months = $diff->y * 12 + $diff->m + $diff->d / 30;

    return (int) round($months);
}

For example it will return (test cases from the unit test):

  • 01.11.2013 - 30.11.2013 - 1 month
  • 01.01.2013 - 31.12.2013 - 12 months
  • 31.01.2011 - 28.02.2011 - 1 month
  • 01.09.2009 - 01.05.2010 - 8 months
  • 01.01.2013 - 31.03.2013 - 3 months
  • 15.02.2013 - 15.04.2013 - 2 months
  • 01.02.1985 - 31.12.2013 - 347 months

Notice: Because of the rounding it does with the days, even a half of a month will be rounded, which may lead to issue if you use it with some cases. So DO NOT USE it for such cases, it will cause you issues.

For example:

  • 02.11.2013 - 31.12.2013 will return 2, not 1 (as expected).
like image 31
Valentin Despa Avatar answered Oct 12 '22 12:10

Valentin Despa


I just wanted to add this if anyone is looking for a simple solution that counts each touched-upon month in stead of complete months, rounded months or something like that.

// Build example data
$timeStart = strtotime("2003-10-17");
$timeEnd = strtotime("2004-03-24");
// Adding current month + all months in each passed year
$numMonths = 1 + (date("Y",$timeEnd)-date("Y",$timeStart))*12;
// Add/subtract month difference
$numMonths += date("m",$timeEnd)-date("m",$timeStart);

echo $numMonths;
like image 27
MaX Avatar answered Oct 12 '22 13:10

MaX