计算两个日期之间的日历月数

时间:2017-02-17 11:21:57

标签: php date

我想计算两天之间日历月的数量。例如:

2017-11-01 => 2017-11-30 = 1 (the same month)
2017-11-01 => 2017-12-01 = 2 (two different calendar months in the date)
2017-11-30 => 2017-12-01 = 2 (the same as above)
2017-11-15 => 2018-06-01 = 8 (6 + 2 different calendar months in the date)

我该怎么做?到目前为止,我有:

$monthStart = new DateTime('2017-11-01');
$monthEnd = new DateTime('2017-12-01');
$dateDiff = $monthStart->diff($monthEnd);
$maxMonths = ($dateDiff->m + ($dateDiff->y*12) + $dateDiff->d>0?1:0);

但它在某些日期不起作用。

此问题与Calculate the number of months between two dates in PHP?不同,因为我想在每次月份数更改时计算月份。不仅在两天之间有30天的差异。查看我提供的示例。

1 个答案:

答案 0 :(得分:1)

$a = "2007-01-01";
$b = "2008-05-31";

$i = date("Ym", strtotime($a));
while($i <= date("Ym", strtotime($b))){
    echo $i."<br>";
    if(substr($i, 4, 2) == "12")
        $i = (date("Y", strtotime($i."01")) + 1)."01";
    else
        $i++;
}

输出:

200701 200702 200703 200704 200705 200706 200707 200708 200709 200710 200711 200712 200801 200802 200803 200804 200805