php - 两个或多个时间间隔之间的持续时间(在 PHP 中)

标签 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)我想要一个逻辑来找到实际不考虑相交时间间隔的持续时间。如果已经回答,请给我路径。提前致谢。 注:是根据考勤数据和值类单计算完成工时

最佳答案

我不知道有什么自动方法可以做到这一点,但我认为最好的方法是将它们转换为整数(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);

NB: I haven't tested this code. Please check it before using it in a live environment.

关于php - 两个或多个时间间隔之间的持续时间(在 PHP 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29094974/

相关文章:

mysql - 对具有多个 ID 的行求和

MySQL - 为每 X 行选择 1

java - 如何创建 Battleship 战舰游戏算法

php - Magento addAttributeToFilter 没有按照我认为应该的方式工作

php - 获取 base64 编码字符串的文件扩展名

php - 如何用phpunit替换方法

mysql - 如何安全地保存密码,但我需要稍后将其作为干净的文本获取?

for-loop - Pascal 中的 For 循环

java - 从文本文件中查找最大值

php - 使用ArrayObject存储数组