简体   繁体   中英

Unexpected result using DatePeriod with DateTime::add()

I expect the following code to generate a list of 5 consecutive days starting with today.

$startDay = new DateTime();
for($i = 0; $i <=4; $i++){
    $courseDay = $startDay->add(new DateInterval("P{$i}D"));
    print_r($courseDay->format('j-M-Y') . "\n");
}

However it gives the following output when run today (21st October 2011):-

21-Oct-2011
22-Oct-2011
24-Oct-2011
27-Oct-2011
31-Oct-2011

I don't see anything wrong with the code, can anybody else? Why is it jumping days?

The code should be refactored as below as DateInterval::add() modifies the instantiated object and then returns the modified version of itself to allow method chaining.

I guess I should have rtm first :)

$startDay = new DateTime();
for($i = 0; $i <=4; $i++){
    print_r($startDay->format('j-M-Y') . "\n");
    $startDay->add(new DateInterval("P1D"));
}

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