How to list all months between two dates

How to list all months between two dates

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

How to list all months between two dates

Generating a sequence of months between two arbitrary dates is a common requirement for financial reporting, analytics dashboards, and time-series data aggregation. However, implementing this logic in PHP often leads to surprising results if you rely on simple numeric iteration without accounting for the calendar structure.

Consider a scenario where you need to list every month from 2010-12-02 to 2012-05-06. A naive approach might define the range as $year_min = 2010, $month_min = 12, and iterate up to $year_max = 2012, $month_max = 5. The resulting code looks like this:

$period = [];
$year_min = 2010;
$year_max = 2012;
$month_min = 12;
$month_max = 5;

for($y = $year_min; $y <= $year_max; $y++) {
    for($m = $month_min; $m <= $month_max; $m++) {
        $period[] = "$y-$m";
    }
}

This logic fails immediately because the inner loop attempts to iterate from 12 down to 5. In a standard for loop, the condition $m <= $month_max is never met when starting at 12 and targeting 5, resulting in an empty array for that iteration cycle. Furthermore, even if you reversed the inequality or fixed the bounds, treating year and month as independent Cartesian coordinates ignores the linear progression of time. You cannot simply increment a "month counter" without handling the carry-over from December to January.

The Linear Iteration Approach

The most robust solution treats time as a continuous sequence rather than nested loops. Instead of calculating start and end years separately, you should calculate the total number of months between the two dates and iterate linearly.

First, parse your input strings into DateTime objects. This ensures you handle leap years and varying month lengths correctly without manual calculation errors.

$start = new DateTime('2010-12-02');
$end   = new DateTime('2012-05-06');
$period = [];

// Calculate the total difference in months
// We add 1 to include the end month itself
$totalMonths = (clone $start)->modify('+1 month')->diff($end, true) + 1; 
// Actually, a more direct way is using Carbon or manual calculation:

A cleaner implementation using DateTime involves creating a loop that increments by exactly one month until reaching the target date. The add() method with 'month' handles the complexity of month lengths automatically.

$start = new DateTime('2010-12-02');
$end   = new DateTime('2012-05-06');
$current = clone $start;

while ($current->format('Y-m') <= $end->format('Y-m')) {
    $period[] = $current->format('Y-m');
    
    $nextMonth = (clone $current)->modify('+1 month');
    // Prevent infinite loops if the end date is before the next calculated month 
    // due to edge cases, though format comparison usually suffices.
}

This approach generates ['2010-12', '2011-01', ... '2012-05']. It naturally handles the transition from December 2010 to January 2011, which the nested loop failed to do. The modify function internally calculates the correct day of the month for the next iteration (e.g., moving from the 31st of a short month might roll over), ensuring you don't get stuck in an infinite loop or skip months.

Handling End Dates and Offsets

One subtle pitfall occurs when the end date is early in a month compared to the start date. For instance, if your range ends on 2012-05-06, do you want to include May 2012? In the example provided, the expected output includes 2012-05.

The comparison $current->format('Y-m') <= $end->format('Y-m') works perfectly here. It strips the day component and compares only the year-month string. As long as your start date's month is less than or equal to the end date's month within the same year, or if the next year has started, the loop terminates correctly.

If you are using a library like Carbon (often preferred in Laravel ecosystems), you can leverage their fluent interface:

use Carbon\Carbon;

$start = Carbon::parse('2010-12-02');
$end   = Carbon::parse('2012-05-06');

$current = $start->copy();
while ($current <= $end) {
    echo $current->format('Y-m') . PHP_EOL;
    $current->addMonth();
}

This is slightly more readable, but the core logic remains the same: linear incrementation based on a date object.

Performance Considerations

For ranges spanning decades or centuries, iterating one month at a time might introduce overhead compared to calculating the total offset mathematically. If performance becomes a bottleneck for massive datasets, you can calculate the number of months using diff properties and create a range array in memory, though this requires handling the day-of-month logic manually if precise truncation is needed. However, for typical reporting needs covering a few years, the iterative modify approach is efficient enough and significantly less error-prone than manual arithmetic on year and month integers.

Ultimately, the key takeaway is to avoid treating dates as independent year and month variables. By leveraging date objects and their built-in arithmetic capabilities, you let the library handle the calendar logic, eliminating the edge cases that break naive loop constructs.

Our network