【问题标题】:Increment DateInterval within loop在循环内增加 DateInterval
【发布时间】:2018-01-11 08:10:52
【问题描述】:

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

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

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

但这似乎是错误的,因为我没有得到任何输出。我不明白我做错了什么,但我不完全知道我用这条线做了什么,老实说,不知道还能去哪里看。我希望我能通过谷歌找到答案,因为这样更快,但我不能。希望能帮到你!

这是完整的循环,之前定义了 $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 ";

非常感谢您!

【问题讨论】:

    标签: php mysql loops while-loop dateinterval


    【解决方案1】:

    问题是:

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

    您不能将日期间隔添加在一起,而只能将日期间隔添加到日期/时间。因此,请使用一些参考日期/时间,并将每个间隔添加到其中。最后,您将参考日期/时间与该结果日期/时间的差异获取最终间隔:

    // 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 ";
    

    【讨论】:

      猜你喜欢
      • 2014-12-12
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-17
      • 2016-08-23
      • 2017-03-26
      • 2021-05-11
      相关资源
      最近更新 更多