Catch all the hours that are between the start time and end time with PHP

2

I'm developing a module and I need to get all the time between 2 hours, start and end . Example:

<?php

$hora_inicial = '08:00';
$hora_final   = '15:00';

?>

Then you would have to list

  

08:00 09:00 10:00 11:00 12:00 13:00 14:00 15:00

How can I do this with PHP?

    
asked by anonymous 28.07.2016 / 03:34

2 answers

1

I have no PC to test, but so it should scroll:

<?php
$start = '08:12';
$end = '15:30';

$st = explode(':', $start);
$ed = explode(':', $end);

for($hour = $st[0]; $hour <= $ed[0]; $hour++)
{
    for($min = $st[1]; $min < 60; $min += 15)
    {
        if($ed[1] >= $min and $hour <= $ed[0])
            echo "Hour: {$hour}:{$min}<br/>";
    }
}

I separate the hour in the colon, and in a time from the start time to the end. Logical if depending on the hours may not happen, for example if the interval is from 23 to 02, but as was not quoted in the question if such a case can occur then I did not treat.     

28.07.2016 / 03:56
0

Another way is to convert the hours in seconds and with function range generate the time :

function listaHorarios($horaInicio, $horaFinal) {
    // Converte os horários em segundos
    $secsInicio = strtotime($horaInicio) - strtotime('today');
    $secsFinal = strtotime($horaFinal) - strtotime('today');

    // Formato de retorno 
    $formato = function ($horario) {
        return date('g:ia', $horario);
    };

    $horarios = range($secsInicio, $secsFinal, 900); // 15min = 900 (60 * 15)
    return array_map($formato, $horarios);
}

How to use:

$horaInicio = '08:00:00';
$horaFinal  = '15:00:00';

$horarios = listaHorarios($horaInicio, $horaFinal);

foreach($horarios as $horario){
    echo "$horario \n";
}

View demonstração

    
28.07.2016 / 18:52