Create time slots with passing date time in PHP

Create time slots by passing start and end time with php. method accepts three parameters startTime, endTime and duration. slots are created from start to end time by breaking with duration .like you need to break time slots with 15 minutes then set duration will be set as 15.

function getTimeSlots($duration, $start, $end)
{
        $time = array();
        $start = new \DateTime($start);
        $end = new \DateTime($end);
        $start_time = $start->format('H:i');
        $end_time = $end->format('H:i');
        $currentTime = strtotime(Date('Y-m-d H:i'));
        $i=0;

        while(strtotime($start_time) <= strtotime($end_time)){
            $start = $start_time;
            $end = date('H:i',strtotime('+'.$duration.' minutes',strtotime($start_time)));
            $start_time = date('H:i',strtotime('+'.$duration.' minutes',strtotime($start_time)));
            
            $today = Date('Y-m-d');
            $slotTime = strtotime($today.' '.$start);

            if($slotTime > $currentTime){
                if(strtotime($start_time) <= strtotime($end_time)){
                    $time[$i]['start'] = $start;
                    $time[$i]['end'] = $end;
                }
                $i++;
            }

        }
        return $time;
}
$duration = 15; // how much the is the duration of a time slot
$start    = '09:00'; // start time
$end      = '10:15'; // end time

getTimeSlots($duration, $start, $end);

Output:

Array
(
    [0] => 09:00 AM - 09:15 AM
    [1] => 09:15 AM - 09:30 AM
    [2] => 09:30 AM - 09:45 AM
    [3] => 09:45 AM - 10:00 AM
    [4] => 10:00 AM - 10:15 PM
)

 

Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.
Yes17
No5
Harinder Singh

Harinder Singh

My name is Harinder Singh and I specialize in Software industry. I consider myself as a life learner. I love learning new concepts, embracing new ideas and reading and searching for innovation.