1

我想创建带有开始、结束时间和中断开始和结束的时间段。
我已经实现了生成时间段,但在 11:10 - 11:25 之间没有休息

实时代码示例

输入变量

$duration = 35; // how much the is the duration of a time slot
$cleanup    = 0; // don't mind this
$start    = '09:00'; // start time
$end      = '12:00'; // end time
$break_start = '11:10'; // break start
$break_end   = '11:25'; // break end

function availableSlots($duration, $cleanup, $start, $end) {
    $start         = new DateTime($start);
    $end           = new DateTime($end);
    $interval      = new DateInterval("PT" . $duration . "M");
    $cleanupInterval = new DateInterval("PT" . $cleanup . "M");
    $periods = array();

    for ($intStart = $start; $intStart < $end; $intStart->add($interval)->add($cleanupInterval)) {
        $endPeriod = clone $intStart;
        $endPeriod->add($interval);

        if ($endPeriod > $end) {
            break;
        }

        $periods[] = $intStart->format('H:i A') . ' - ' . $endPeriod->format('H:i A');
    }


    return $periods;
}

函数将生成此输出:

09:00 AM - 09:35 AM
09:35 AM - 10:10 AM
10:10 AM - 10:45 AM
10:45 AM - 11:20 AM
11:20 AM - 11:55 AM

我需要实现的是上午 11:10 到上午 11:25 的休息时间,这将被排除在结果之外。

$break_start = '11:10';
$break_end   = '11:25';
4

1 回答 1

0

试试这个...我已经修改了你的功能

function availableSlots($duration, $cleanup, $start, $end, $break_start, $break_end) {
    $start         = new DateTime($start);
    $end           = new DateTime($end);
    $break_start           = new DateTime($break_start);
    $break_end           = new DateTime($break_end);
    $interval      = new DateInterval("PT" . $duration . "M");
    $cleanupInterval = new DateInterval("PT" . $cleanup . "M");
    $periods = array();

    for ($intStart = $start; $intStart < $end; $intStart->add($interval)->add($cleanupInterval)) {
        $endPeriod = clone $intStart;
        $endPeriod->add($interval);

        if(strtotime($break_start->format('H:i A')) < strtotime($endPeriod->format('H:i A')) && strtotime($endPeriod->format('H:i A')) < strtotime($break_end->format('H:i A'))){
            $endPeriod = $break_start;
            $periods[] = $intStart->format('H:i A') . ' - ' . $endPeriod->format('H:i A');
            $intStart = $break_end;
            $endPeriod = $break_end;
            $intStart->sub($interval);
        }else{
            $periods[] = $intStart->format('H:i A') . ' - ' . $endPeriod->format('H:i A');
        }
    }


    return $periods;
}

$duration = 35; // how much the is the duration of a time slot
$cleanup    = 0; // don't mind this
$start    = '09:00'; // start time
$end      = '12:00'; // end time
$break_start = '11:10'; // break start
$break_end   = '11:25'; // break end
availableSlots($duration, $cleanup, $start, $end, $break_start, $break_end);

结果将是:

Array
(
    [0] => 09:00 AM - 09:35 AM
    [1] => 09:35 AM - 10:10 AM
    [2] => 10:10 AM - 10:45 AM
    [3] => 10:45 AM - 11:10 AM
    [4] => 11:25 AM - 12:00 PM
)
于 2018-04-01T10:42:23.743 回答