Calculate the number of months between two dates in PHP?

前端 未结 12 1757
无人及你
无人及你 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 06:12

    This is a simple method I wrote in my class to count the number of months involved into two given dates :

    public function nb_mois($date1, $date2)
    {
        $begin = new DateTime( $date1 );
        $end = new DateTime( $date2 );
        $end = $end->modify( '+1 month' );
    
        $interval = DateInterval::createFromDateString('1 month');
    
        $period = new DatePeriod($begin, $interval, $end);
        $counter = 0;
        foreach($period as $dt) {
            $counter++;
        }
    
        return $counter;
    }
    

提交回复
热议问题