Calculate number of calendar months that two dates

2019-08-30 04:32发布

问题:

I want to calculate, using PHP or MySQL, the number of calendar months that are encompassed between two dates.

For example:

February 3, 2015 (2015-02-03) and April 10, 2015 (2015-04-10) would be three months (February, March, April. Also, February 28, 2015 (2015-02-28) and April 1, 2015 (2015-04-01) would be three months (February, March, April).

So the actual number of calendar months don't really matter... I just want to know how many months on a calendar fall between two months.

I can't come up with a simple/elegant way to do this with PHP or MySQL.

回答1:

Try this:

$from = new DateTime('February 28, 2015');
$to = new DateTime('April 1, 2015');
$months = 1 + ($to->format('Y') - $from->format('Y')) * 12 + $to->format('n') - $from->format('n');

echo $months ;

demo



回答2:

You can use this to get total months between two dates

    $date1 = '2015-10-25';
    $date2 = '2016-07-20';        

    $year1 = date('Y', strtotime($date1));
    $year2 = date('Y', strtotime($date2));

    $month1 = date('m', strtotime($date1));
    $month2 = date('m', strtotime($date2));

    $diff = (($year2 - $year1) * 12) + ($month2 - $month1);
    echo $diff;

Hope this helps. Thanks.