我正在通过登录时间和注销时间之间的差异来计算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;
timeoflogin和logouttime的格式为-05:03:53 pm。 $ duration提供正确的结果。我想将所有持续时间添加为变量,并在while循环后打印。请帮帮我。
您可以简单地将循环内已经计算出的差异添加到另一个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);
现在您需要做的就是按照您想要的方式对其进行格式化。