Pick up all hours that are between start time and end time with PHP

Asked

Viewed 621 times

2

I’m developing a module and I need to take every hour between 2 hours, initial and final. Example:

<?php

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

?>

Then you’d 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 ?

  • Do you only need the time? The date is not important ?

2 answers

1


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

<?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 divide the hour into the two points, and in a split I go from the initial hour to the final. Logical if depending on the hours may not happen, for example if the interval is from 23 to 02, but as it was not mentioned in the question whether it can occur such case then I did not treat.

  • Your code worked, but in case you have minutes ? Type `$start = '08:15';'

  • How would it be in the case? Because it was not specifically quoted in the question, with minutes the output would be '8:15', '9:15, and so on? And in the case I mentioned in the question, would an interval enter as 23:00 to 02:00? For if yes the answer code would not work.

  • Actually the code I’m doing it has hours that go from 8:00 to 8:00 and the breaks are 15 minutes, ie 8:00, 8:15, 8:45, 9:00 etc... I need to pick up these intervals along with the time until I arrive at the $end

  • I edited putting minutes, remembering that it is functional only when the initial time is less than the final (in digit)

  • I tested the code and it’s 99%.. The problem is it counts down to the minutes 45 then it jumps to the next hour +30 of the previous minute.. For example: 08:00, 08:15, 08:30, 08:45, 09:15 ... He doesn’t set the time with 00

  • 1

    I’ve done such a trick: if($min == 60){$hour = $hour+1;$min = '00';} and worked (in addition to exchanging < 60 for <= 60

Show 1 more comment

0

Another way is to convert the hours into seconds and with the function range generate the schedules:

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);
}

Mode of use:

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

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

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

See demonstração

Browser other questions tagged

You are not signed in. Login or sign up in order to post.