Iterate schedules with carbon and laravel

0

Hi, I have the following code with carbon where I want to get an array with the start time until the final hour every 30 min. It does not work for me Any suggestions.

            $inicio = $horario[0]->end_date; // 08:00:00
            $final = $horario[1]->start_date; // 12:00:00

            $cerrado = array(); //added
            $h = 0;
            $i = Carbon::parse($inicio)->toTimeString();
            $f = Carbon::parse($final)->toTimeString();

            while($i <= $f){
                $cerrado[] = Carbon::parse($inicio)->copy()->addMinute($h)->format('H:i:s');

                $h=$h+30;
            }
            dd($cerrado);
    
asked by Juan Jose 28.11.2018 в 17:37
source

1 answer

0

Without using carbon and based on the classes provided by PHP DateTime , DateInterval and DatePeriod you can do it in the following way:

<?php
$inicio = new DateTime( '2018-11-28 08:00:00');
$fin = new DateTime( '2018-11-28 12:00:00');

$intervalo = new DateInterval('PT30M');

$fechas = new DatePeriod($inicio, $intervalo, $fin);

foreach($fechas as $fecha){
    echo $fecha->format("d-m-Y H:i:s") . "<br>";
}
?>

Result:

28-11-2018 08:00:00
28-11-2018 08:30:00
28-11-2018 09:00:00
28-11-2018 09:30:00
28-11-2018 10:00:00
28-11-2018 10:30:00
28-11-2018 11:00:00
28-11-2018 11:30:00

If you only want to show the hours or with a different format, it would be enough to set $fecha->format("d-m-Y H:i:s") , info in DateTime::format .

    
answered by 28.11.2018 в 18:49