Calculating shift hours worked and detecting

这一生的挚爱 提交于 2019-12-06 09:16:46

问题


I have a problem. My English is pretty bad. I need to do an overtime calculation with PHP. There is already a code for this. But when the working time is more than 2 days, the calculation is wrong.

Working Start: 2018-09-09 13:43

Working End: 2018-09-11 07:13

Result: 07:18 | 04:00 | 04:00 | 02:00 | 17:18

I can't figure out the problem, please help. I'd like to give you more details, but I'm pretty bad. I hope you understand me.

Thanks.

<?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

来源:https://stackoverflow.com/questions/53016394/calculating-shift-hours-worked-and-detecting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!