我的问题是,我与“ h:s:m”相加超过5次 但我无法计算时间。首先是错误的计算日期,其次datetime不会超过24小时,但我不想仅显示日期。
我已经尝试过计算时间,但是每次都会得出错误的结果。
$worktime = 0;
$worktimePause = 0;
$UserID = $_POST['workerButtons'];
$_SESSION['cur_user_id'] = $_POST['workerButtons'];
$sql = "SELECT * FROM worktime WHERE `user_id` = '$UserID'";
foreach ($mysql->query($sql) as $row) {
$dif = gmdate("H:i:s",(strtotime($row["time_end"]) - strtotime($row["time_start"])));
$worktime = gmdate("H:i:s", strtotime($worktime) + strtotime($dif)); #worktime should be the result in h:m:s for example 29:20:21
echo "<tr><td>" . date('d.m.Y', strtotime($row["date"])). "</td><td>" . $row["time_start"] . "</td><td>". $row["time_end"]. "</td><td>" . $dif . "</td><td>". calculateHours($dif)."</td></tr>";
}
答案 0 :(得分:1)
我建议使用PHP的DateTime和DateInterval类-它们内置了许多与日期和时间相关的功能。例如:
<?php
$clockInDatetime = new \DateTime('2019-06-07 13:59:03');/* Clocked in at 1:59:03 pm */
$clockOutDatetime = new \DateTime('2019-06-08 02:05:56');/* Clocked out at 2:05:56 am the following day */
$interval = $clockInDatetime->diff($clockOutDatetime);
?>
<table>
<tbody>
<tr>
<td>Clocked-in DateTime:</td>
<td><?php echo $clockInDatetime->format('Y/m/d @ H:i:s a '); ?></td>
</tr>
<tr>
<td>Clocked-out DateTime:</td>
<td><?php echo $clockOutDatetime->format('Y/m/d @ H:i:s a '); ?></td>
</tr>
<tr>
<td>Duration (H:i:s):</td>
<td><?php echo $interval->format('%h:%i:%s'); ?></td>
</tr>
</tbody>
</table>
您甚至可以像这样添加多个日期时间/间隔(考虑午餐时间/休息时间):
<?php
$shiftInPre = new \DateTime('2019-06-07 13:59:03');/* Clocked in at 1:59:03 pm */
$shiftOutPre = new \DateTime('2019-06-07 18:30:25');/* Clocked out for lunch at 6:30:25 pm */
$shiftInPost = new \DateTime('2019-06-07 19:29:12');/* Clocked in from lunch at 7:30:12 pm */
$shiftOutPost = new \DateTime('2019-06-08 02:05:56');/* Clocked out at 2:05:56 am the following day */
/* Shift 1 duration */
$interval1 = $shiftInPre->diff($shiftOutPre);
/* Shift 2 duration */
$interval2 = $shiftInPost->diff($shiftOutPost);
/* Use new date to determine total duration of this days shifts */
$dateBase = new \DateTimeImmutable();
$dateSum = $dateBase->add($interval1);
$dateSum = $dateSum->add($interval2);
$shiftInterval = $dateBase->diff($dateSum);
?>
<table>
<tbody>
<tr>
<td>Shift 1:</td>
<td><?php echo $interval1->format('%h:%i:%s'); ?></td>
</tr>
<tr>
<td>Shift 2:</td>
<td><?php echo $interval2->format('%h:%i:%s'); ?></td>
</tr>
<tr>
<td>Total:</td>
<td><?php echo $shiftInterval->format('%h:%i:%s'); ?></td>
</tr>
</tbody>
</table>