Printing schedules at predetermined intervals

Asked

Viewed 781 times

0

I’m trying to make a code that will print the hours in a certain 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 15 interval I want printed schedules 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 should be taken as the first value of the array. I’m running the logic of the code on paper and I can’t find the problem..

  • The way you are trying to do it is not possible to succeed. The solution goes through classe DateTime . A good tutorial can be found at https://www.devmedia.com.br/manipulando-datas-com-php/32966

  • If any answer has solved your problem do not forget to mark it as accepted. See how and why in this post https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079

3 answers

1


The creation of a class object DateTime is the easiest way to manipulate dates in your application.

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

These are the concepts applied in the script to arrive at the expected result. The code is well commented and there will be no difficulties to locate 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 reason why the condition was imposed if($result == ($interval-1) || $result == ($interval)){ , ie = 14 or = 15

Ideone - $interval = 15

Ideone - $interval = 3

Another way to get the same result, without taking into account 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

0

The way you tried it would be possible, but it will be bad practice! In this case the ideal would be to use the native PHP function strtotime,and within the function pass as the current time parameter and the time you want to add the current time, in which case we pass the time and minutes you want to add, this will return a timestamp, we will convert this timestamp at a readable time, this with the help of function date also native to PHP, where it will receive as parameters the expected return and the 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 that the time is correct

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

  • I think, that does not answer his question , because he wanted to display the values in a range , because he does not want to add the time but rather locate the values that match the interval

  • @Viniciusshiguemori is right! My answer was based on the beginning of the question "I’m trying to make a code that will print the hours in a certain range."

  • I’ll edit the code!

  • blz, I was working on the code tbm, but his way is much more elaborate than mine, waiting to see how it goes

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');
}
  • 2

    I could put a brief explanation of your answer?

  • Sure. I used it for a project. Generates an array of times in a 24h window where it adds 30min (in Dateinterval) every hour and already starts the array with the time you set in $start.

Browser other questions tagged

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