簡體   English   中英

Php DateTime::setDate() 不適用於第一次 DatePeriod 迭代

[英]Php DateTime::setDate() not working on first DatePeriod iteration

在一些報告中,我循環遍歷接下來的 6 個月並找出開始/結束范圍以進行計算。 對於這個循環的每個月,除了第一個月外,setDate() 都能正常工作。

# Loop over the next 6 months (from start of this month)
$now = new DateTime("first day of this month", new DateTimeZone("Pacific/Auckland"));

$end = clone $now;
$end->modify("+6 month");

$int = new DateInterval("P1M");
$period = new DatePeriod($now, $int, $end);

# For each month, work out the start/end dates and times for the reports
foreach ($period as $month) {
    $start = clone $month;
    $start->setDate($start->format("Y"), $start->format("m"), 1);
    $start->setTime(0, 0, 0);

    $end = clone $month;
    $end->setDate($end->format("Y"), $end->format("m"), $end->format("t"));
    $end->setTime(23, 23, 59);

    # Dumping out data here shows weirdness below
}

無論如何,第一個月的結束日期都是第一個月。 即使我手動將其設置為任何其他有效的日期整數。 我已經把它剝離到裸露的例子中,它仍然在做。

string(19) "2016-05-01 00:00:00"
string(19) "2016-05-01 23:23:59" <- Huh? This should be 31
===========
string(19) "2016-06-01 00:00:00"
string(19) "2016-06-30 23:23:59"
===========
string(19) "2016-07-01 00:00:00"
string(19) "2016-07-31 23:23:59"
...etc...

我在 php 5.5.26

使用某些相關格式創建 DateTime 對象時 PHP 中的錯誤。

PHP 錯誤 #63863 DateTime:setDate() 修改后未使用日期(“...的最后一天”)

這似乎只有在使用某些相對格式創建 DateTime 對象時才會發生,例如'last day of next month' 'first day of this month''first day of this month' ,但是'last sat of July 2008'不會導致錯誤。

感謝評論中的邁克

簡單的解決方法,使用不同的方法來創建初始$now DateTime 對象。

https://eval.in/577984

# Loop over the next 6 months (from start of this month)
$now = new DateTime("now", new DateTimeZone("Pacific/Auckland"));
$now->setDate($now->format("Y"), $now->format("m"), 1);

$end = clone $now;
$end->modify("+6 month");

$int = new DateInterval("P1M");
$period = new DatePeriod($now, $int, $end);

# For each month, work out the start/end dates and times for the reports
foreach ($period as $month) {
    $start = clone $month;
    $start->setDate($start->format("Y"), $start->format("m"), 1);
    $start->setTime(0, 0, 0);

    $end = clone $month;
    $end->setDate($end->format("Y"), $end->format("m"), $end->format("t"));
    $end->setTime(23, 23, 59);

    echo $start->format('Y-m-d H:i:s') . "\n";
    echo $end->format('Y-m-d H:i:s') . "\n";
}

暫無
暫無

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

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