PHP: Loop through all months in a date range?

后端 未结 7 1046
误落风尘
误落风尘 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 14:06

    Try

    $start = $month = strtotime('2009-02-01');
    $end = strtotime('2011-01-01');
    while($month < $end)
    {
         echo date('F Y', $month), PHP_EOL;
         $month = strtotime("+1 month", $month);
    }
    

    Mind the note http://php.net/manual/de/datetime.formats.relative.php

    Relative month values are calculated based on the length of months that they pass through. An example would be "+2 month 2011-11-30", which would produce "2012-01-30". This is due to November being 30 days in length, and December being 31 days in length, producing a total of 61 days.

    As of PHP5.3 you can use http://www.php.net/manual/en/class.dateperiod.php

    0 讨论(0)
提交回复
热议问题