Calculate time difference in php

Asked

Viewed 13,579 times

2

I am trying to show how many hours an employee has worked, however the ways I tried presented incorrect values. Follow the same below:

This returns the difference with 3 hours and 2 minutes less:

$horario1 = '16:05:00';
$horario2 = '10:16:53';   
date('H:i:s',(strtotime($horario1) - strtotime($horario2))));

And this returned 21:00:06 for the hours above exemplified:

date('H:i:s',($horario1 - $horario2)));

1 answer

6


I did it this way and it worked correctly:

//Calcula o tempo de upload
$entrada = $horario1;
$saida = $horario2;
$hora1 = explode(":",$entrada);
$hora2 = explode(":",$saida);
$acumulador1 = ($hora1[0] * 3600) + ($hora1[1] * 60) + $hora1[2];
$acumulador2 = ($hora2[0] * 3600) + ($hora2[1] * 60) + $hora2[2];
$resultado = $acumulador2 - $acumulador1;
$hora_ponto = floor($resultado / 3600);
$resultado = $resultado - ($hora_ponto * 3600);
$min_ponto = floor($resultado / 60);
$resultado = $resultado - ($min_ponto * 60);
$secs_ponto = $resultado;
//Grava na variável resultado final
$tempo = $hora_ponto.":".$min_ponto.":".$secs_ponto;
echo $tempo;
  • It worked correctly. Could you explain to me why of multiplication and division by 3600 and 60?

  • 1

    3600 turns seconds into hours and vice versa. 60 minutes into seconds.

  • I think it’s cool as didactic, but in practice PHP already has simpler functions and ready to solve the problem. strtotime( '1970-01-01 '.$horario1 ) already returns the value in seconds.

  • 1

    Now, if it’s a case where the time, minute and second are already separated, definitely I also think better to use mathematics than the textual interpretation of strtotime. However, +1

  • Another interesting way to get the total seconds having hours and minutes apart is this: mktime ($hora,$minuto,$segundo,1,1,1970)

  • @Bacco, you’re right. But I broke my head a lot and it was this mathematical solution that best solved my case. Thanks for the considerations.

Show 1 more comment

Browser other questions tagged

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