在循环内递增 DateInterval

Increment DateInterval within loop

我有一个 mySQL table 有 2 个包含日期的列。 while 循环将它们中的每一个放入一个变量中:$start_date 和 $end_date,计算它们之间的时间并使用 diff() 将其放入一个新变量 $since_start 中;据我所知,使用 diff() 会导致 DateInterval Class.

现在我想在 'while' 循环期间建立一个总和并将其存储在 $total_received 变量中。在搜索网络和 Whosebug 之后,我尝试的最后一件事是

$total_received->add(new DateInterval($since_start));

但这似乎是错误的,因为我没有得到任何输出。我不明白我做错了什么,但我不完全知道我用这条线做了什么,老实说,也不知道该往哪里看。我希望我能通过 google 找到答案,因为那样更快,但我做不到。希望对您有所帮助!

这是完整的循环,其中 $total_received 变量在之前定义并在之后输出。

//Set variable for lifetime received total
$total_received = 0;

if ($result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo 
          $row["id"] ." "
        . $row["donor"]." ";
        $start_date = new DateTime($row["start"]);
        $end_date = new DateTime($row["end"]);
        $since_start =  $start_date->diff($end_date);
        $total_received->add(new DateInterval($since_start));
        echo $since_start->format('%h')." Hours ".$since_start->format('%i')." Minutes "
        . $row["subject"] ." " 
        . $row["complete"] ."<br>";
    }
} else {
    echo "No lifetime received yet";
}

echo $total_received->format('%h')." Hours ".$total_received->format('%i')." Minutes ";

非常感谢您!

问题在于:

  • $total_received = 0 将该变量初始化为一个数字,它没有您稍后使用的 add 方法。
  • $since_start 已经是 DateInterval,所以 new DateInterval($since_start) 没有多大意义,会触发错误

您不能将日期间隔加在一起,只能将日期间隔添加到一个 date/time。所以使用一些参考 date/time,并将每个间隔添加到它。最后,您将参考 date/time 与结果 date/time 相差得到最终间隔:

// Create the "interval" as a start/end reference date
$ref_start = new DateTime("00:00");
$ref_end = clone $ref_start;

if ($result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo 
          $row["id"] ." "
        . $row["donor"]." ";
        $start_date = new DateTime($row["start"]);
        $end_date = new DateTime($row["end"]);
        $since_start =  $start_date->diff($end_date);
        // Move the end date/time of the reference period
        $ref_end->add($since_start);
        echo $since_start->format('%h')." Hours ".$since_start->format('%i')." Minutes "
        . $row["subject"] ." " 
        . $row["complete"] ."<br>";
    }
} else {
    echo "No lifetime received yet";
}
// Only now convert the reference period to an interval
$total_received = $ref_start->diff($ref_end);

echo $total_received->format('%h')." Hours ".$total_received->format('%i')." Minutes ";