Listing Months Between Two Dates
In various applications, it becomes necessary to list or iterate through months within a specified date range. To accomplish this, we present two solutions in PHP, catering to different PHP versions.
PHP 5.3 and Later
<code class="php">$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"; }</code>
PHP 5.4 or Newer
<code class="php">$start = (new DateTime('2010-12-02'))->modify('first day of this month'); $end = (new DateTime('2012-05-06'))->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"; }</code>
Note that modifying the start and end dates to the first day of each month ensures a complete listing of the desired months, preventing cases where February might be skipped if the current day is higher than its last day.
The above is the detailed content of How to List Months Between Two Dates in PHP?. For more information, please follow other related articles on the PHP Chinese website!