【问题标题】:PHP add time duration in while loopPHP在while循环中添加持续时间
【发布时间】:2020-03-20 12:44:32
【问题描述】:

我正在通过登录时间和注销时间的差异来计算 while 循环中的持续时间。我想在变量中添加所有持续时间并将其打印出来。 我正在使用的代码是 -

$totaltimespent = new DateTime;
$totaltimespent->setTime(0, 0);
$timespent= (strtotime($totaltimespent->format("H:i:s")));

while ($row  = mysqli_fetch_array($result)) {
echo $row['timeoflogin'];
echo $row['logouttime'];

$startTime = new DateTime($row['timeoflogin']);
$endTime = new DateTime($row['logouttime']);
$duration = $startTime->diff($endTime);

echo $duration->format("%H:%I:%S");
$converttime= (strtotime($duration->format("%H:%I:%S")));

$timespent  = date("H:i:s",$converttime+$timespent);
}
echo $timespent;

登录时间和注销时间的格式为 - 下午 5:03:53。 $duration 给出了正确的结果。我想在变量中添加所有持续时间并在while循环后打印。请帮帮我。

【问题讨论】:

  • $duration 的输出是什么
  • $duration 的输出是 05:53:26
  • 不使用DateTime可能更容易,只需在开头和结尾获取time(),然后将差异格式化为HH:MM:SS。

标签: php date time add


【解决方案1】:

您可以简单地将您在循环中计算的差值添加到另一个 DateTime 对象中,并获得它们之间的最终差值。

$totalStart = new DateTime('today'); // this will create it with time 00:00:00
$totalEnd = new DateTime('today'); // we will use this to add the intervals from the loop

while ($row  = mysqli_fetch_array($result)) {
    ...
    $startTime = new DateTime($row['timeoflogin']);
    $endTime = new DateTime($row['logouttime']);
    $duration = $startTime->diff($endTime);
    $totalEnd->add($duration);
    ...
}

$totalTimeSpent = $totalStart->diff($totalEnd);

现在您需要做的就是按照您想要的方式对其进行格式化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-23
    • 2016-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多