dtq26360 2017-02-17 11:21
浏览 38
已采纳

计算两个日期之间的日历月数[重复]

This question already has an answer here:

I would like to calculate number of calendar months between two days. For example:

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)

How can I do that? So far I have:

$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);

But it doesn't work for some dates.

This QUESTION IS DIFFERENT from: Calculate the number of months between two dates in PHP? as I want to calculate the month every time the number for month changes. Not only when there is a 30 days difference between two days. Check the examples I have provided.

</div>
  • 写回答

1条回答 默认 最新

  • duankan6894 2017-02-17 12:43
    关注
    $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++;
    }
    

    output:

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法