首页 > 解决方案 > 计算轮班工作时间并检测

问题描述

我有个问题。我的英语很差。我需要用 PHP 做一个加班计算。已经有一个代码。但是当工作时间超过2天时,计算是错误的。

工作开始:2018-09-09 13:43

工作结束:2018-09-11 07:13

结果:07:18 | 04:00 | 04:00 | 02:00 | 17:18

我无法弄清楚问题,请帮助。我想给你更多的细节,但我很糟糕。我希望你能理解我。

谢谢。

<?php
function intersection($s1, $e1, $s2, $e2,$day) {
    return subintersection($s1,$e1,$s2,$e2)+subintersection($s1,$e1,$s2+$day,$e2+$day);
}
function subintersection($s1, $e1, $s2, $e2) {
    if ($e1 < $s2)
            return 0;
    if ($s1 > $e2)
            return 0;
    if ($s1 < $s2)
            $s1 = $s2;
    if ($e1 > $e2)
            $e1 = $e2;
    return $e1 - $s1;
}
function minuteToHours($time, $format = '%02d:%02d') {
  if ($time < 1) {
    return;
  }
  $hours = floor($time / 60);
  $minutes = ($time % 60);
  return sprintf($format, $hours, $minutes);
}
function calculateWork($strstart, $strend, $arg = NULL){

  $day= 3600*24;
  $strS = strtotime($strstart);
  $strE = strtotime($strend);
  $date_start = date('Y-m-d', $strS);
  $date_end = date('Y-m-d', $strE);
  $hour_start = date('H:i', $strS);
  $hour_end = date('H:i', $strE);
  $start = strtotime($hour_start);
  $end = strtotime($hour_end);
  if($date_start != $date_end){
    $end = $end + 3600*24;
  }
  $tip1_start = strtotime("06:00");
    $tip1_end = strtotime("20:00");

    $tip2_start = strtotime("20:00");
    $tip2_end = strtotime("00:00") + 3600*24;

    $tip3_start = strtotime("00:00");
    $tip3_end = strtotime("04:00");

    $tip4_start = strtotime("04:00");
    $tip4_end = strtotime("06:00");
  $tip1 = intersection( $start, $end, $tip1_start, $tip1_end, $day) / 60;
  $tip2 = intersection( $start, $end, $tip2_start, $tip2_end, $day) / 60;
  $tip3 = intersection( $start, $end, $tip3_start, $tip3_end, $day) / 60;
  $tip4 = intersection( $start, $end, $tip4_start, $tip4_end, $day) / 60;
  if(null !== minuteToHours($tip1, '%02d:%02d')){
    $t1 = minuteToHours($tip1, '%02d:%02d');
  }
  if(null !== minuteToHours($tip2, '%02d:%02d')){
    $t2 = minuteToHours($tip2, '%02d:%02d');
  }
  if(null !== minuteToHours($tip3, '%02d:%02d')){
    $t3 = minuteToHours($tip3, '%02d:%02d');
  }
  if(null !== minuteToHours($tip4, '%02d:%02d')){
    $t4 = minuteToHours($tip4, '%02d:%02d');
  }
  $topla = $tip1 + $tip2 + $tip3 + $tip4;
  $total = minuteToHours($topla, '%02d:%02d');
  return "{$t1}|{$t2}|{$t3}|{$t4}|{$total}";
}
echo calculateWork("2018-09-09 13:43", "2018-09-11 07:01");
//07:18|04:00|04:00|02:00|17:18

标签: phpdatetimeclock

解决方案


推荐阅读