在laravel中需要动态时间的空闲时间段

时间:2018-06-11 09:14:05

标签: php laravel date datetime time

有一个音高和音高有自己的开始时间和结束时间(例如从上午8:00到下午7:00)。 多场比赛已经安排了一段时间。 (例如从上午8:30到上午9:00,上午10:00到上午10:30) 所以现在我要计算的是球场上的可用时间。 我的代码在这里:

$pitchStart = '2018-06-11 08:00 AM';
$pitchClose = '2018-06-11 09:00 PM';

$firstGameStart = '2018-06-11 09:30 AM';
$firstGameEnd = '2018-06-11 10:00 AM';

$secondGameStart = '2018-06-11 10:00 AM';
$secondGameEnd = '2018-06-11 10:30 AM';

$thirdGameStart = '2018-06-11 11:00 AM';
$thirdGameEnd = '2018-06-11 11:30 AM';


$Result = [
    [0] => ['freeSlotStart' => '2018-06-11 08:00 AM','freeSlotEnd' => '2018-06-11 09:30 AM'],
    [1] => ['freeSlotStart' => '2018-06-11 10:30 AM','freeSlotEnd' => '2018-06-11 11:00 AM'],
    [2] => ['freeSlotStart' => '2018-06-11 11:30 AM','freeSlotEnd' => '2018-06-11 09:00 PM'],
];

1 个答案:

答案 0 :(得分:2)

下面的代码显示了如何获取所有使用的插槽(基于间隔)。

<?php

$pitchStart = new DateTime('2018-06-11 08:00 AM');
$pitchClose = new DateTime('2018-06-11 09:00 PM');

$games = [
    [
        'start' => new DateTime('2018-06-11 09:00 AM'),
        'end' => new DateTime('2018-06-11 10:00 AM')
    ],
    [
        'start' => new DateTime('2018-06-11 10:30 AM'),
        'end' => new DateTime('2018-06-11 10:43 AM')
    ],
    [
        'start' => new DateTime('2018-06-11 11:00 AM'),
        'end' => new DateTime('2018-06-11 11:55 AM')
    ]
];

//This is the time slots interval
$slot_interval = new DateInterval("PT30M"); //30 Minutes

//Get all slots between $pitchStart and $pitchClose
$all_slots = [];

$slots_start = $pitchStart;
$slots_end = $pitchClose;

//This is how you can generate the intervals based on $pitchStart / $pitchClose and $slot_interval
while($slots_start->getTimestamp() < $slots_end->getTimestamp()) {
    $all_slots[] = [
        'start' => clone $slots_start, 
        'end' => (clone $slots_start)->add($slot_interval)
    ];
    $slots_start->add($slot_interval);
}

function slots_used_by_game($slots, $games, $slot_interval) {
    $slots_taken = [];

    foreach($games as $game){
        $game_duration = $game['end']->diff($game['start']);
        $game_duration_in_minutes = (float)($game_duration->h * 60 + $game_duration->i);

        $number_of_slots = ceil($game_duration_in_minutes / $slot_interval);

        foreach($slots as $key => $slot) {
            if($game['start'] <= $slot['start']) {
                $slots_taken = array_merge($slots_taken, array_slice($slots, $key, $number_of_slots));
                break;
            }
        }
    }
    return $slots_taken;
}

$used_slots = slots_used_by_game($all_slots, $games, 30);

//Print them all for testing
foreach($all_slots as $slot) {
    echo $slot['start']->format('Y-m-d H:i'). ' - '.$slot['end']->format('Y-m-d H:i').PHP_EOL;
    echo ((in_array($slot, $used_slots)) ? 'NOT AVAILABLE' : 'AVAILABLE').PHP_EOL;
    echo PHP_EOL;
}