Printing times with predetermined intervals

1

I'm trying to make a code that will print the hours at a given interval.

<?php 
//Array com os horarios que possam ser imprimidos
$hora = array('13:55:40','13:56:40','13:58:41','13:59:40','14:01:00','14:02:00','14:04:40',
'14:05:00','14:07:10','14:08:00','14:10:23', '14:11:23','14:13:39','14:14:23','14:16:39',
'14:17:23','14:19:13','14:20:23','14:22:40', '14:21:23','14:25:07', '14:26:23', '14:55:40');

//Intervalo que o usuario escolherá entre 3, 15, 30 ou 60
$interval = 15;

$base = explode(":", $hora[0]);
$horaBase = $base[0];
$minBase = $base[1];
$j = 1;

$tam = count($hora);
echo "Interval: {$interval} <br>";
echo "Tamanho do array: {$tam} <br>";
echo "<br>0: ".$hora[0]."<br>";

while($j < $tam){
    $time = explode(":", $hora[$j]);

    if($time[1] >= ($minBase+$interval)){
        echo $j." : ".$hora[$j]."<br>";
        $minBase += $interval;
    }
    if($horaBase < $hora[0]){
        $minBase -= 60;
        $horaBase = $hora[0];
    }
    $j++;
}?>

For example, using a range of 15 I want the printed times to be:

  

13:55:40, 14:10:23, 14:25:07

But this code is printing:

  

13:55:40, 13:58:41, 13:59:40, 14:55:40

For this case, the base value must be taken as the first value of the array. I am passing the code logic on paper and I can not seem to find the problem ..

    
asked by anonymous 23.11.2017 / 19:58

3 answers

1
  

Creating an object of class DateTime is the easiest way to manipulate dates in your application.

     

When we have two objects of class DateTime we can compare them with the diff() method that returns a DateInterval object and represents the difference between the two dates, which we can return according to the desired format using the date_format () function.

     

These are the concepts applied in the script to achieve the expected result. The code is well commented and there will be no difficulty in locating each concept above applied to the code.

//Array com os horarios que possam ser imprimidos
$hora = array('13:55:40','13:56:40','13:58:41','13:59:40','14:01:00','14:02:00','14:04:40',
'14:05:00','14:07:10','14:08:00','14:10:23', '14:11:23','14:13:39','14:14:23','14:16:39',
'14:17:23','14:19:13','14:20:23','14:22:40', '14:21:23','14:25:07', '14:26:23', '14:55:40');

//Intervalo que o usuario escolherá entre 3, 15, 30 ou 60
$interval = 15;

//valor de base o primeiro valor do array.
$val1 = $hora[0];

print $val1;

for ($i=0;$i<(count($hora)-1);$i++) {

    $val2 = $hora[$i+1];

    //Instanciando objetos DateTime
    $datetime1 = new DateTime($val1);
    $datetime2 = new DateTime($val2);

    //Retorna a diferença entre dois objetos DateTime.
    $intervalo = $datetime1->diff($datetime2);

    //Retorna a dìferença de acordo com um formato informado, neste caso minutos
    $result = $intervalo->format('%i');

    //imprime o valor cuja diferença é dada por $interval
    if($result == ($interval-1) || $result == ($interval)){
         print ", ".$val2;
         //atribui o valor encontrado $val2 em $val1 para buscar
         //próxima diferença $interval a partir deste
         $val1 = $val2;
    }

}
  

NOTE: Note that the difference between 13:55:40, 14:10:23, is 14 minutos e 43 segundos and not 15 minutes why the condition if($result == ($interval-1) || $result == ($interval)){ was imposed, that is = 14 or = 15

Ideone - $ interval = 15

Ideone - $ interval = 3

Another way to get the same result, regardless of the seconds, is:

//Array com os horarios que possam ser imprimidos
$hora = array('13:55:40','13:56:40','13:58:41','13:59:40','14:01:00','14:02:00','14:04:40',
'14:05:00','14:07:10','14:08:00','14:10:23','14:11:23','14:13:39','14:14:23','14:16:39',
'14:17:23','14:19:13','14:20:23','14:22:40', '14:21:23','14:25:07', '14:26:23', '14:55:40');

//Intervalo que o usuario escolherį entre 3, 15, 30 ou 60
$interval = 3;

$val1 = $hora[0];

print $val1;

//formata para am/pm sem segundos
$val1P = date( 'g:i a', strtotime($val1) );

for ($i=0;$i<(count($hora)-1);$i++) {

    $val2 = $hora[$i+1];

    //formata para am/pm sem segundos
    $val2P = date( 'g:i a', strtotime($val2) );

    $datetime1 = new DateTime($val1P);
    $datetime2 = new DateTime($val2P);

    $intervalo = $datetime1->diff($datetime2);

    $result = $intervalo->format('%i');

    if($result == $interval){

         print ", ".$val2;
         $val1P = $val2P;

    }

}

Ideone - $ interval = 3

    
24.11.2017 / 02:02
0

The way you tried it would be possible, but it would be a bad practice! In this case, the ideal would be to use the native function of PHP strtotime , and within the function to pass as the current time parameter and the time that you want to add the current time, in this case we will give you the hour and minutes you want to add, this will return a timestamp , we will convert this timestamp to a readable hour, this with the help of the date function also native to PHP, where you will receive as expected the expected return and timestamp you want to convert.

date_default_timezone_set("America/Sao_Paulo");

//Use a variável abaixo para definir uma hora inicial
//$horaDefinida = '10:10';

//Use a variável abaixo para pegar a hora automaticamente
$horaDefinida = date('H:i');
$tempoEmMinutos = 15;
$quantidadeIntervalos = 10;


$interval = 0;
while($interval <= $quantidadeIntervalos){

    $horaNova = strtotime("$horaDefinida + ".$tempoEmMinutos." minutes");
    $horaNovaFormatada = date("H:i:s",$horaNova);   
    $horaDefinida = $horaNovaFormatada;

    echo $horaNovaFormatada;
    echo "<br>";

    $interval++;

}


//Hora com acrescimos a partir de um array

$horas = array('13:55:40','13:56:40','13:58:41','13:59:40','14:01:00','14:02:00','14:04:40',
'14:05:00','14:07:10','14:08:00','14:10:23', '14:11:23','14:13:39','14:14:23','14:16:39',
'14:17:23','14:19:13','14:20:23','14:22:40', '14:21:23','14:25:07', '14:26:23', '14:55:40');


foreach ($horas as $hora) {

    $horaNova = strtotime("$hora + ".$tempoEmMinutos." minutes");
    $horaNovaFormatada = date("H:i:s",$horaNova);

    echo 'Hora antiga:'.$hora.' Hora nova: '.$horaNovaFormatada.'<br>';

}
  

Note that the 'date_default_timezone_set' function has been added to set a default location so the time is correct

     

Read more about the 'date' and 'strtotime' functions

    
23.11.2017 / 21:00
0

See if it helps:

$start = new \DateTime('08:00');
$times = 12 * 2; // 24 hours * 30 mins in an hour
$result[0] = $start->format('H:i');
for ($i = 0; $i < $times - 1; $i++) {
    $result[] = $start->add(new \DateInterval('PT30M'))->format('H:i');
}
    
01.12.2017 / 23:35