简体   繁体   中英

How to loop through months of a PHP DatePeriod class?

I need to get all the numeric months spanned by a date range. So for a range 18 Jul 2014 - 4 Sep 2014, give me 7,8,9.

This is getting me close:

$start = new DateTime('2014-07-18');
$interval = new DateInterval('P1M');
$end = new DateTime('2014-09-04');
$period = new DatePeriod($start, $interval, $end);

foreach ($period as $dt) {
    echo $dt->format('n') . PHP_EOL;
}

It returns 7 and 8, but no 9 for September because it's not a full P1M interval. I'd like to get 7,8,9 regardless of where the start/end days fall in the month.

Am I going in the right direction?

Found an answer on this page: http://forums.phpfreaks.com/topic/275341-find-what-months-a-date-range-covers/

$start = new DateTime('2014-07-18');
$end = new DateTime('2014-09-04');

$inc = DateInterval::createFromDateString('first day of next month');
$end->modify('+1 day');

$p = new DatePeriod($start,$inc,$end);

foreach ($p as $d)
 echo $d->format('n') . PHP_EOL;

Outputs:

7 8 9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM