Loop through all months in a date range?

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


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;
}

The accepted answer is not the proper way.

I tried this snippet and it does not work properly. If your start date is the end of the month and the end date is the start of the 3rd month.

For example: 2014-08-31 - 2014-10-01

Expected should be.

  • August
  • September
  • October

The better solution is:

$start    = new DateTime('2010-12-02');
$start->modify('first day of this month');
$end      = new DateTime('2012-05-06');
$end->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period   = new DatePeriod($start, $interval, $end);

foreach ($period as $dt) {
    echo $dt->format("Y-m") . "<br>\n";
}

Reference: How to list all months between two dates