Calculate time difference

Asked

Viewed 92 times

0

tabela config

Hello friends all right ? So I have the following problem that I’ve never solved before and I don’t even know where to start. I am creating a scheduling system have the top table to config in this scheme I have 3 rooms, the opening hours and the interval timer.

I need to generate a select for the company to select the desired time with the limit of 3 selection per hour. Example:

8:05
8:10
8:15
8:20
and so on until lunch time comes and continue after lunch and go until the end of the day

Could you give me a glimpse of how I can do that? Thank you very much

  • I don’t even know how to help, but I’ll give you some ideas. Are the schedules as string? I’ve tried to do something similar... Then there is the strtotime function or something like that that helps pass the string to time...

  • So it occurred to me to take the difference between the times in minutes type in the afternoon gives 270 minutes divided by the timer of the 54 loop ai I pick the initial time and I add 5 minutes to each given loop

  • You can turn everything into seconds, or... add 5 minutes at a time. $horacompleta + 5 ? :/

  • 1

    finishing to assemble the code here if it works I will post it here, but this is the idea

2 answers

1


Hello it wasn’t very clear what you want but I did a function here that might help you.

/**
 * Retorna array de horarios para ser utilizado em select
 *
 * @param string $horarioInicio
 * @param string $horarioFinal
 * @param int $timer | números em minutos a ser adicionado
 */
function obtemHorariosParaSelect($horarioInicio, $horarioFinal, $timer)
{
    $time = DateTime::createFromFormat('H:i:s', $horarioInicio);
    $horarios[] = $horarioInicio;
    while ($horarioInicio <= $time->format('H:i:s') && $horarioFinal > $time->format('H:i:s')) {
        $time->modify("+$timer minutes");
        $horarios[] = $time->format('H:i:s');
    }

    return $horarios;
}

$horarios = array_merge(
    obtemHorariosParaSelect('08:00:00', '12:00:00', 5),
    obtemHorariosParaSelect('13:30:00', '18:00:00', 5)
);

output:

array(
    '08:00:00',
    '08:05:00',
    ...
    '12:00:00',
    '13:30:00',
    ...
    '18:00:00',
)
  • hehehehe made a giant code to solve this, I will study yours and use it which is best. posted mine below

  • When working with dates it is recommended to use the function datetime.

  • is much better than my solution. Thank you very much

0

function difDeHoras($hIni, $hFinal)
{        
   // Separa á hora dos minutos
   $hIni = explode(':', $hIni);
   $hFinal = explode(':', $hFinal);

   // Converte a hora e minuto para segundos
   $hIni = (60 * 60 * $hIni[0]) + (60 * $hIni[1]);
   $hFinal = (60 * 60 * $hFinal[0]) + (60 * $hFinal[1]);

   // Verifica se a hora final é maior que a inicial
   if(!($hIni < $hFinal)) {
       return false;
   }

   // Calcula diferença de horas
   $difDeHora = $hFinal - $hIni;

   //Converte os segundos para Hora e Minuto
   $tempo = $difDeHora / (60 * 60);
   $tempo = explode('.', $tempo); // Aqui divide o restante da hora, pois se não for inteiro, retornará um decimal, o minuto, será o valor depois do ponto.
   $hora = $tempo[0];
   @$minutos = (float) (0) . '.' . $tempo[1]; // Aqui forçamos a conversão para float, para não ter erro.
   $minutos = $minutos * 60; // Aqui multiplicamos o valor que sobra que é menor que 1, por 60, assim ele retornará o minuto corretamente, entre 0 á 59 minutos.
   $minutos = explode('.', $minutos); // Aqui damos explode para retornar somente o valor inteiro do minuto. O que sobra será os segundos
   $minutos = $minutos[0];
//Aqui faz uma verificação, para retornar corretamente as horas, mas se não quiser, só mandar retornar a variavel hora e minutos
   if (!(isset($tempo[1]))) {
       if($hora == 1){
           return $hora*60;
       } else {
           return $hora*60;
       }
   } else {
       if($hora == 1){
           if($minutos == 1){
               return $hora*60+$minutos;
           } else {
               return $hora*60+$minutos;
           }
       } else {
           if($minutos == 1){
               return $hora*60+$minutos;
           } else {
               return $hora*60+$minutos;
           }
       }
   }
}
function converteHorasEmMinutos($horas) { 
    $t = explode(".", $horas); 
    $h = $t[0]; 
    if(isset($t[1])) { 
        $m = $t[1]; 
    }else{ 
        $m = "00"; 
    } 
    $mm = ($h * 60); 
    return $mm; 
} 

function converteMinutosEmHoras($time, $format = '%02d:%02d') {
    if ($time < 1) {
        return;
    }
    $hours = floor($time / 60);
    $minutes = ($time % 60);
    return sprintf($format, $hours, $minutes);
}

$loopManha = difDeHoras($configuracao->horario_ini, $configuracao->horario_alm_ini)/$configuracao->timer;
$loopTarde = difDeHoras($configuracao->horario_alm_fim, $configuracao->horario_fim)/$configuracao->timer;
?>




<?php
                    $horarioManha = converteHorasEmMinutos($configuracao->horario_ini);
                    $x = 0;
                    while($x < $loopManha-1) {
                       $x++;
                       $horarioManha = $horarioManha+5;
                       $horarioManhaH = converteMinutosEmHoras($horarioManha);
            ?>
                       <option value="<?=$horarioManha?>" data-subtext="Manhã"><?=$horarioManhaH?></option>
    <?php
      }
    ?>

Browser other questions tagged

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