两个或多个时间间隔之间的持续时间(以PHP表示)

时间:2015-03-17 09:03:44

标签: php mysql logic

我的时间间隔如下,

1-  07:00:00 to 09:30:00 (duration 02:30:00)
2-  08:00:00 to 11:00:00 (duration 03:00:00)

但实际组合持续时间为07:00:00 - 11:00:00(Dur 04:00:00)。当我们添加2个单独的持续时间时,它将给出结果5:30:00 ..就像这种不同的组合可能发生(1-7,5-8,9-10,6-9:30)我想要一个逻辑来找到实际的持续时间而不考虑相交的时间间隔。如果它已经回答了,请给我一条路径。提前致谢。 注意:这是根据出勤数据和值班单来计算工作的持续时间

2 个答案:

答案 0 :(得分:0)

我不知道有任何自动化方法,但IMO最好的方法是将它们转换为整数(Unix时间戳),然后一次处理两个。然后你可以找到最早的开始时间和最新的结束时间来计算订单,然后检查早期的结束时间是否与最新的开始时间重叠。

function compareTimes($start1, $end1, $start2, $end2)
{
    $earliest = $start1 <= $start2 ? 1 : 2;
    $latest = $end1 >= $end2 ? 1 : 2;

    if ($earliest == $latest) 
    {
        $end = 'end'.$latest;
        $start = 'start'.$earliest;
        return ($$end - $$start);
    }

    // Check to see if there is any overlap.
    $earlyEnd = 'end'.$earliest;
    $lateStart = 'start'.$latest;
    if ($earlyEnd >= $lateStart)
    {
        $start = 'start'.$earliest;
        $end = 'end'.$latest;
        return ($$end - $$start);
    }
    // If there is no overlap we just total the duration of the two.
    return (($end1 - $start1) + ($end2 - $start2));

}

$start1 = strtotime('01/01/1970 07:00');
$end1 = strtotime('01/01/1970 09:30');
$start2 = strtotime('01/01/1970 08:00');
$end2 = strtotime('01/01/1970 11:00');
$totalDuration = compareTimes($start1, $end1, $start2, $end2);
  

注意:我还没有测试过这段代码。在现场环境中使用之前请检查它。

答案 1 :(得分:0)

enter code here

function compareTimes($start,$end)  
 {
 $count=count($start);
 for($i=0;$i<$count;$i++)
 {
  for($j=0;$j<$count;$j++)
  {
   if($j==$i)
   {

   }
   elseif($start[$j]>=$start[$i] and $start[$j]<=$end[$i]) 
   {
     if($end[$j]>=$start[$i] and $end[$j]<=$end[$i]) 
     {
       $start[$j]="0";
       $end[$j]="0";
     }  
     else
     {
        $end[$i]=$end[$j];
        $start[$j]="0";
       $end[$j]="0";
     }
   }

  }
 }
 $dur=0;
 $count1=count($start);
 for($i=0;$i<$count1;$i++)
 {
  $dur1=$end[$i]-$start[$i];
  $dur=$dur1+$dur;
 }
  return $dur;   
 }

//期间的例子5-6,4-8&amp; 8-9

  $start=array("5","4","8");

  $end=array("6","8","9");
  $check=compareTimes($start,$end);
相关问题