How to get all months between two dates in PHP?

前端 未结 6 1822
旧巷少年郎
旧巷少年郎 2021-01-29 16:41

I have 2 dates. I want to get all months with total days in each.

How can I do this in PHP?

For example

$date1 = \'2013-11-13\'         


        
6条回答
  •  北海茫月
    2021-01-29 17:15

    You can use the DateTime class along with cal_day_in_month() like this

    $datetime1 = "2014-02-15";
    $datetime2= "2013-03-15";
    
    $date1 = new DateTime($datetime1);
    $date2 = new DateTime($datetime2);
    
    while (date_format($date2, 'Y-m') <= date_format($date1, 'Y-m'))
    {
    
        $date2 = $date2->add(new DateInterval('P1M'));
    
        echo $date2->format('Y-m')." | ".cal_days_in_month(CAL_GREGORIAN, $date2->format('m'), $date2->format('Y'))."
    "; }

提交回复
热议问题