PHP: Loop through all months in a date range?

后端 未结 7 1071
误落风尘
误落风尘 2020-12-02 13:32

If I have a start date (say 2009-02-01) and an end date (say 2010-01-01), how can I create a loop to go through all the dates (months) in the range

7条回答
  •  鱼传尺愫
    2020-12-02 13:57

    I have a method which is optimal in results :

    $begin = new DateTime( '2014-07-14' );
    $end = new DateTime( '2014-08-01' );
    $end = $end->modify( '+1 month' );
    $interval = DateInterval::createFromDateString('1 month');
    
    $period = new DatePeriod($begin, $interval, $end);
    
    foreach($period as $dt) {
        var_dump($dt->format( "m" ));
    }
    

    A plus for the method of @Glavic

提交回复
热议问题