我有一个 mySQL 表,其中有 2 列,其中包含日期。 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 ";
提前非常感谢您!
最佳答案
问题在于:
$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 ";
关于php - 循环内增加 DateInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45488989/