How to List Months Between Two Dates in PHP?

DDD
Release: 2024-11-03 15:53:03
Original
692 people have browsed it

How to List Months Between Two Dates in PHP?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template