Calculate the number of months between two dates in PHP?

前端 未结 12 1748
无人及你
无人及你 2020-12-01 05:12

Without using PHP 5.3\'s date_diff function (I\'m using PHP 5.2.17), is there a simple and accurate way to do this? I am thinking of something like the code below, but I don

12条回答
  •  长情又很酷
    2020-12-01 05:55

    How about this:

    $d1 = new DateTime("2009-09-01");
    $d2 = new DateTime("2010-09-01");
    $months = 0;
    
    $d1->add(new \DateInterval('P1M'));
    while ($d1 <= $d2){
        $months ++;
        $d1->add(new \DateInterval('P1M'));
    }
    
    print_r($months);
    

提交回复
热议问题