How to get an interval between a range of hours?

1

I'm trying to get hours between a range of hours, example:

I have 2 hours: 23:00:00 (The start) and 01:00:00 (The end)

Now, through a for loop, I try to get the initial time from 30 to 30 minutes until it reaches the end. Example:

23:00:00
23:30:00
00:00:00
00:30:00
01:00:00

I am using the following script:

public function test($horas){

    for($i=0;$i<count($horas);$i++){

        for($j=$horas[$i]->hora_ini;
            $j <= $hora[$i]->hora_fin;
            $j = date("H:i:s", strtotime($j)+(30*60))){
            echo $j.'<br />';
        }
    }
}

But it does not work, it only works when there are hours for example from 08:00:00 to 14:00:00 but not from 23:00:00 to 01:00:00

    
asked by Alejandro 09.12.2017 в 02:24
source

1 answer

1

I have created a function that keeps the period of hours with the pre-established intervals in minutes (modifiable).

Using the class and its methods of DateTime .

Watch Demo Online

function intervaloHora($hora_inicio, $hora_fin, $intervalo = 30) {

    $hora_inicio = new DateTime( $hora_inicio );
    $hora_fin    = new DateTime( $hora_fin );
    $hora_fin->modify('+1 second'); // Añadimos 1 segundo para que nos muestre $hora_fin

    // Si la hora de inicio es superior a la hora fin
    // añadimos un día más a la hora fin
    if ($hora_inicio > $hora_fin) {

        $hora_fin->modify('+1 day');
    }

    // Establecemos el intervalo en minutos        
    $intervalo = new DateInterval('PT'.$intervalo.'M');

    // Sacamos los periodos entre las horas
    $periodo   = new DatePeriod($hora_inicio, $intervalo, $hora_fin);        

    foreach( $periodo as $hora ) {

        // Guardamos las horas intervalos 
        $horas[] =  $hora->format('H:i:s');
    }

    return $horas;
}

print_r( intervaloHora( '23:00:00', '01:00:00' ) );

//** Resultado **// 
Array
(
    [0] => 23:00:00
    [1] => 23:30:00
    [2] => 00:00:00
    [3] => 00:30:00
    [4] => 01:00:00
)
    
answered by 09.12.2017 / 11:35
source