"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to List Months Between Two Dates in PHP?

How to List Months Between Two Dates in PHP?

Published on 2024-11-08
Browse:538

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

$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") . "
\n"; }

PHP 5.4 or Newer

$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") . "
\n"; }

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3