如何计算总时数:分钟考勤休息时间?

2022-09-04 00:00:00 collections php laravel query-builder

我有一个$attendace变量包含来自Laravel查询构建器的集合:

$attendance = collect(DB::table('attendance_copy')->where('emp_number', Auth::user()->emp_number)->where('date_created', $datenow)->get());

这是结果:

[
   {
      "row_id":65,
      "emp_number":"IPPH0004",
      "time_stamp":"01:00:00",
      "attendance_status":"Punch In",
      "date_created":"2021-10-02"
   },
   {
      "row_id":68,
      "emp_number":"IPPH0004",
      "time_stamp":"07:30:00",
      "attendance_status":"Start Break",
      "date_created":"2021-10-02"
   },
   {
      "row_id":69,
      "emp_number":"IPPH0004",
      "time_stamp":"08:00:00",
      "attendance_status":"End Break",
      "date_created":"2021-10-02"
   },
   {
      "row_id":70,
      "emp_number":"IPPH0004",
      "time_stamp":"08:30:00",
      "attendance_status":"Start Break",
      "date_created":"2021-10-02"
   },
   {
      "row_id":71,
      "emp_number":"IPPH0004",
      "time_stamp":"09:00:00",
      "attendance_status":"End Break",
      "date_created":"2021-10-02"
   }
];

我到目前为止所做的(当只有1个start breakend break时有效):

$startbreak = strtotime(( isset( $attendance->where('attendance_status', 'Start Break')->first()->time_stamp  ) == null ? "00:00:00" : $attendance->where('attendance_status', 'Start Break')->first()->time_stamp));
$endbreak = strtotime(( isset( $attendance->where('attendance_status', 'End Break')->first()->time_stamp  ) == null ? "00:00:00" : $attendance->where('attendance_status', 'End Break')->first()->time_stamp));


$minsbreak = date('i',$endbreak - $startbreak);

但在我的例子中,每个员工全天都会记录很多休息时间。我想计算一下员工的休息时间:

从上面的集合(12hr格式)来看,它应该是01:00 total hrs。从7:30 to 8:00 is 30mins8:30 to 9:00 is another 30mins开始。将有5个最长中断时间。

这可能吗?或者我应该重新设计我的出席表?谢谢


解决方案

此答案假定集合已由employee_number筛选,并且Start Break之后的状态必须为End Break

$total_break_time = 0;

for ($i = 0; $i < count($attendance); ++$i) {
    if ($i == 0)
        continue;

    if ($attendance[$i-1]['attendance_status'] == 'Start Break') {
        $previous_timestamp = strtotime($attendance[$i-1]['date_created'] . ' ' . $attendance[$i-1]['time_stamp']);
        $current_timestamp = strtotime($attendance[$i]['date_created'] . ' ' . $attendance[$i]['time_stamp']);
        $total_break_time += ($current_timestamp - $previous_timestamp);
    }
}

echo gmdate('H:i:s', $total_break_time) . PHP_EOL;

$total_break_time是秒数。gmdate函数将其转换为小时、分钟、秒,返回01:00:00

相关文章