Loop through all months in a date range?

Viewed 80761

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?

8 Answers

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

Based on Gordon's response this is the way I actually work when you need to get all the months between.

$end = strtotime(date("Y-m-01"));
$start = $month = strtotime("-12 months", $end);

while ( $month < $end ) {
    echo date("Y-m-d", $month);
    $month = strtotime("+1 month", $month);
}

This is the result if I execute this code now:

2018-05-01
2018-06-01
2018-07-01
2018-08-01
2018-09-01
2018-10-01
2018-11-01
2018-12-01
2019-01-01
2019-02-01
2019-03-01
2019-04-01

Notice that this doesn't include the current month. If you need to include current month, you can set the "$end" variable to the first day of the next month.

$current_first_day_of_the_month = date("Y-m-01");
$end = strtotime("$current_first_day_of_the_month +1 month");
$start = $month = strtotime("-12 months", $end);

This could be useful in a reverse loop (from future to past)

$start = $month = strtotime("2023-07-01"); //You must use the same day date to prevent problems (and we want a loop by months)
$end = strtotime("2021-12-01");

while($month>=$end) { //use > if don't want the last month

  //Insert you code here

  echo date('M Y', $month) . " "; //just to show it works

  //the next line is the key. You can reverse jump by a month and PHP understand changes of year
  $month = mktime(0, 0, 0, date("m", $month)-1, date("d", $month), date("Y", $month) );
}
Related