CodeBriefly
Tech Magazine

Create Time Slots in PHP for Given Time

1 12,442

Get real time updates directly on you device, subscribe now.

In this article, we will discuss “Create Time Slots in Php”. Check the following code snippet. With this code, we can create time slots for a given interval and time range.

function getTimeSlot($interval, $start_time, $end_time)
{
    $start = new DateTime($start_time);
    $end = new DateTime($end_time);
    $startTime = $start->format('H:i');
    $endTime = $end->format('H:i');
    $i=0;
    $time = [];
    while(strtotime($startTime) <= strtotime($endTime)){
        $start = $startTime;
        $end = date('H:i',strtotime('+'.$interval.' minutes',strtotime($startTime)));
        $startTime = date('H:i',strtotime('+'.$interval.' minutes',strtotime($startTime)));
        $i++;
        if(strtotime($startTime) <= strtotime($endTime)){
            $time[$i]['slot_start_time'] = $start;
            $time[$i]['slot_end_time'] = $end;
        }
    }
    return $time;
}

 

For e.g: create time slots for 30 minutes from 10 AM to 13 PM.

$slots = getTimeSlot(30, '10:00', '13:00');
echo '<pre>';
print_r($slots);

 

Output:

Array
(
    [1] => Array
        (
            [slot_start_time] => 10:00
            [slot_end_time] => 10:30
        )

    [2] => Array
        (
            [slot_start_time] => 10:30
            [slot_end_time] => 11:00
        )

    [3] => Array
        (
            [slot_start_time] => 11:00
            [slot_end_time] => 11:30
        )

    [4] => Array
        (
            [slot_start_time] => 11:30
            [slot_end_time] => 12:00
        )

    [5] => Array
        (
            [slot_start_time] => 12:00
            [slot_end_time] => 12:30
        )

    [6] => Array
        (
            [slot_start_time] => 12:30
            [slot_end_time] => 13:00
        )

)

If you like our content, please consider buying us a coffee.
Thank you for your support!
Buy Me a Coffee

Get real time updates directly on you device, subscribe now.

1 Comment
  1. Luc says

    I want to generate a time slot for a doctor which is every 1 hour in Laravel but i got stuck with the code and

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. AcceptRead More