PHP: Loop through all months in a date range?

后端 未结 7 1075
误落风尘
误落风尘 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条回答
  •  猫巷女王i
    2020-12-02 13:56

    Example of DateTime, DateInterval and DatePeriod class combination :

    $start = new DateTime('2009-02-01');
    $interval = new DateInterval('P1M');
    $end = new DateTime('2011-01-01');
    $period = new DatePeriod($start, $interval, $end);
    
    foreach ($period as $dt) {
        echo $dt->format('F Y') . PHP_EOL;
    }
    

提交回复
热议问题