How to get all months between two dates in PHP?

前端 未结 6 1887
旧巷少年郎
旧巷少年郎 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:24

    This is what i came up with:

    $arr_months = array();
    $date1 = new DateTime('2013-11-15');
    $date2 = new DateTime('2014-02-15');
    $month1 = new DateTime($date1->format('Y-m')); //The first day of the month of date 1
    while ($month1 < $date2) { //Check if the first day of the next month is still before date 2
        $arr_months[$month1->format('Y-m')] = cal_days_in_month(CAL_GREGORIAN, $month1->format('m'), $month1->format('Y')); //Add it to the array
        $month1->modify('+1 month'); //Add one month and repeat
        }
    
    print_r($arr_months);
    

    It creates an associative array with the month as key and the number of days as value. The array created from the example would be:

    Array
    (
        [2013-11] => 30
        [2013-12] => 31
        [2014-01] => 31
        [2014-02] => 28
    )
    

    With a foreach loop you will be able to scroll trough the array easily.

提交回复
热议问题