簡體   English   中英

使用DatePeriod和DateTime :: add()的意外結果

[英]Unexpected result using DatePeriod with DateTime::add()

我希望以下代碼從今天開始連續5天生成列表。

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

但是,在今天(2011年10月21日)運行時,它將提供以下輸出:

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

我看不到代碼有什么問題,其他人可以嗎? 為什么是跳躍的日子?

由於DateInterval :: add()修改了實例化的對象,然后返回其自身的修改版本以允許方法鏈接,因此代碼應按以下方式進行重構。

我想我應該先擁有rtm :)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM