首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >循环内增量DateInterval

循环内增量DateInterval
EN

Stack Overflow用户
提问于 2017-08-03 15:46:26
回答 1查看 262关注 0票数 1

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

现在,我想在'while‘循环中构建一个和,并将它存储在$total_received变量中。在搜索完网络和堆栈溢出之后,我最后一次尝试的是

代码语言:javascript
运行
复制
$total_received->add(new DateInterval($since_start));

但这似乎是错误的,因为我没有任何产出。我不明白我做错了什么,但我不知道我到底在做什么,老实说,也不知道还能去哪里看。我希望我能找到答案谷歌,因为这是更快,但我不能。我希望你能帮助!

下面是带有$total_received变量的完整循环,它在前面定义,然后输出。

代码语言:javascript
运行
复制
//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 ";

非常感谢您提前!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-03 16:33:06

问题是:

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

不能将日期间隔一起添加,但只能将日期间隔添加到日期/时间。因此,使用一些参考日期/时间,并将每个间隔添加到该日期/时间。最后,取引用日期/时间与该结果日期/时间的差值,以获得最后的间隔:

代码语言:javascript
运行
复制
// 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 ";
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45488989

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档