Hours calculation

Asked

Viewed 667 times

3

I need to calculate the exact time that a given record has to be analyzed.

Each registration has a intermission where it can be analysed and, a maximum value in hours, referring to deadline for analysis.

Example

inserir a descrição da imagem aqui

End time = Registration date + Deadline = 26/12/2014 04:24:31

But I need the off-hours to be ignored, which means:

  • The day 25 would be counted only 01:35:29, because the interval is until 22h
  • It would return the count from 08h, finalizing the exact time 26/12/2014 14:24:31

My current solution is a loop for each record:

$incremento = 0
$cadastro = "26/12/2014 04:24:31"
$intervalo_inicial = 8
$intervalo_final = 10
$prazo = 8

while ($incremento <> $prazo) {
    if ($cadastro >= $intervalo_inicial) and ($cadastro <= $intervalo_final) {
        $incremento += 1
    }
    // adiciona 1 hora
    $cadastro = date($cadastro, strtotime('1 hour'));
}

However, calculating 100,000 record makes the task very slow. Any type of solution is valid, database, formula, logic..

1 answer

2


You can use division to know how many full days you used and how many hours left.

To avoid confusion in this example (due to two different values worth 8), I changed the deadline to 7 hours. Also, in the version actually I would use the minimum unit of time count to do the math (seconds or milliseconds, depends on what you are using) but in the example I represented everything using hours to be clearer.

$tempo_inicio = 20:24:31 - 08:00:00  // = 12:24:31
$prazo = 07:00:00
$tempo_fim = $hora_inicio + $prazo // = 19:24:31

$horas_por_dia = 22:00:00 - 08:00:00 // = 14:00:00

// quociente e resto da divisão
$dias_gastos = $tempo_fim / $horas_por_dia  // 1
$horas_ultimo_dia = $tempo_fim % $horas_por_dia // 5:24:31

$dia_fim = $dia_inicio + $dias_gastos // dia 26
$hora_fim = 8:00:00 + $horas_ultimo_dia // 13:24:31
  • Perfect @hugomg, just changed the $dias_gastos = $prazo/24, in some situations was counting +1 day

  • Which cases were giving the wrong value? Dividing by 24 you do not ignore the hours out of range...

Browser other questions tagged

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