我正在尝试为7天工作周期间的员工添加总工作时间,因为代码对我不起作用,不确定我做错了什么因为我不是PHP
专家,想法好吗?
<?php
$time1 = $row_Roster['sunday_start'];
$time2 = $row_Roster['sunday_end'];
list($hours, $minutes, $seconds) = explode(':', $time1);
$startTimestamp = mktime($hours, $minutes, $seconds);
list($hours, $minutes, $seconds) = explode(':', $time2);
$endTimestamp = mktime($hours, $minutes, $seconds);
$add = $endTimestamp - $startTimestamp;
if($seconds < 0) {
$seconds+=60*60*24;
}
$seconds = $add % 60;
$minutes = ($add / 60) % 60;
$hours = floor($add / (60 * 60));
$sunday = sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
echo $sunday;
if ($sunday >8)
echo ('</br><span class="smallred">Long Shift</span>');
?>
有意义吗?
list($hours, $minutes, $seconds) = explode(':', $time1);
$Timestamp1 = mktime($hours, $minutes, $seconds);
list($hours, $minutes, $seconds) = explode(':', $time2);
$Timestamp2 = mktime($hours, $minutes, $seconds);
list($hours, $minutes, $seconds) = explode(':', $time3);
$Timestamp3 = mktime($hours, $minutes, $seconds);
list($hours, $minutes, $seconds) = explode(':', $time4);
$Timestamp4 = mktime($hours, $minutes, $seconds);
$add = $Timestamp1 + $Timestamp2 + $Timestamp3 + $Timestamp4;
if($seconds < 0) {
$seconds+=60*60*24;
}
$seconds = $add % 60;
$minutes = ($add / 60) % 60;
$hours = floor($add / (60 * 60));
$total = sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
echo $total;
?>
答案 0 :(得分:2)
你这样做会变得复杂。
首先将所有格式化的日期放入数组($formattedWorkTimeWeekdays
)。
然后使用array_map()
查看每一天并计算每天的总秒数并将其保存在$secondsWorkTimeWeekdays
。
在此之后,您可以将所有秒数与array_sum()
相加,并在变量$totalSecondsWorkTimeWeek
中获得本周的总工作量(以秒为单位)。
最后只需计算出小时,分钟和秒数。
<?php
$formattedWorkTimeWeekdays = [
$monday,
$tuesday,
$wednesday,
$thursday,
$friday,
$saturday,
$sunday,
];
$secondsWorkTimeWeekdays = array_map(function($formattedWorkTimeDay){
list($hours, $minutes, $seconds) = explode(":", $formattedWorkTimeDay);
return ($hours * 3600) + ($minutes * 60) + $seconds;
}, $formattedWorkTimeWeekdays);
$totalSecondsWorkTimeWeek = array_sum($secondsWorkTimeWeekdays);
$hoursWorkTimeWeek = $totalSecondsWorkTimeWeek / 3600;
$minutesWorkTimeWeek = ($totalSecondsWorkTimeWeek % 3600) / 60;
$secondsWorkTimeWeek = ($totalSecondsWorkTimeWeek % 3600 % 60);
echo $total = sprintf('%02d:%02d:%02d', $hoursWorkTimeWeek, $minutesWorkTimeWeek, $secondsWorkTimeWeek);
?>
修改强>
在您编辑后,您有两个完全不同的代码,这些代码根本不相关。对于您的第一次修订,我给出了上面的答案。
现在,在您编辑的代码中,您似乎只有2个日期。您可以创建两个DateTime
对象并从中获取差异,例如
$workTimeStart = new DateTime($row_Roster['sunday_start']);
$workTimeEnd = new DateTime($row_Roster['sunday_end']);
$workTimeDifference = $workTimeStart->diff($workTimeEnd);
echo $workTimeDifference->format("%h hours %i minutes %s seconds");
答案 1 :(得分:0)
您可以使用gmdate function:
,而不是计算和调用sprintf
//the same code summing the weekdays seconds
$add = $Timestamp1 + $Timestamp2 + $Timestamp3 + $Timestamp4;
print gmdate("H:i:s", $add);