Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

chesterBot's avatar

Carbon Time Intervals for booking

I wonder if there is a Carbon method that can divide start and end time into intervals before I start implementing my own method. Basically I have an interval a start and end time like this, 9:00 am and 5:00 pm, from 9 to 5 there are 8 working hours and an interval of 2 hours mean (8/2) 4 intervals of 2 hours. expected output 9:00 am - 11:00 am 11:00 am - 1:00 pm 1:00 pm - 3:00 pm 3:00 pm - 5:00 pm

0 likes
5 replies
chesterBot's avatar

That is what i did..


            $data = [];
            $startTime = Carbon::parse($startTime);
            $cutTime = Carbon::parse($cutTime);
            while ($startTime->lte($cutTime)) {
                $to = $startTime->copy()->addHours($interval);
                array_push($data, $startTime->toTimeString() . '-' . $to->toTimeString());
                $startTime = $to;
            }

mabdullahsari's avatar

You asked whether there was something built into the Carbon API to do what you wish to do, but then you proceed to implement it yourself.

I'm confused. The snippet I provided should be perfectly fine...

chesterBot's avatar

With CarbonPeriod this will also output same result.it looks much cleaner


           $intervals = CarbonPeriod::since($startTime)->hours($interval)->until($cutTime)->toArray();
            foreach ($intervals as $interval) {
                $to = next($intervals);
                if ($to !== false) {
                    array_push($data, $interval->toTimeString() . '-' . $to->toTimeString());
                }
            }

1 like

Please or to participate in this conversation.