Subtraction of hours in php

8

When I subtract the time the result is "0" I want it to be in the time format, for example: 19:38:20 - 19:37:00 = 00:01:20.

Note: The "time" values of the database I'm assigning to "$ time1" and "$ time2" are in varchar format. I have already tested both and are in the correct format, but when subtracting it is not in the time format as stated before ...

code:

<html>
  <head>
    <meta charset="UTF-8">
</head>
<body>

<?php

include "../../conexao.php";

// primeira parte 1

$sql = "SELECT * FROM tempo";
$result = $conn->query($sql);


while($row = $result->fetch_assoc()) {
$id = $row["id"];
$tempo1 = $row["tempo"];



$sql = "DELETE FROM tempo WHERE id='$id'";
if ($conn->query($sql) === TRUE) {
} else {
echo "Erro ao tentar deletar: " . $conn->error;
}

echo "$tempo1 <br>";



// segunda parte 2.2

$sql = "SELECT * FROM tempo2";
$result = $conn->query($sql);

while($row = $result->fetch_assoc()) {
$id = $row["id"];
$corrida = $row["corrida"];
$nome1 = $row["nome"];
$numero = $row["numero"];
$tempo2 = $row["tempo"];

echo "$tempo2 <br>"; 


$sql = "DELETE FROM tempo2 WHERE id='$id'";
if ($conn->query($sql) === TRUE) {
} else {
echo "Erro ao tentar deletar: " . $conn->error;
}

$tempo = $tempo2 - $tempo1;
echo "$tempo <br>";

}

}
    
asked by anonymous 25.04.2016 / 00:46

4 answers

11

You can use the DateTime () class to find the difference between two dates.

/**
 * @param $dateStart - Data inicial
 * @param $dateEnd - Data final
 * @param $format  - Formato esperado de saida
 */
function dateDiff( $dateStart, $dateEnd, $format = '%a' ) {

    $d1     =   new DateTime( $dateStart );

    $d2     =   new DateTime( $dateEnd );

    //Calcula a diferença entre as datas
    $diff   =   $d1->diff($d2, true);   

    //Formata no padrão esperado e retorna
    return $diff->format( $format );

}

The types of outputs available are% Y Years,% m Months,% d Days,% H Hours,% i Minutes,% s Seconds. For your case, you will pass in the last parameter the following string: '% H:% i:% s'

I hope it helps.

    
25.04.2016 / 02:24
10

Note: I did not remember this one and I ended up answering a duplicate with a solution even more elegant than here (and obviously without using DateTime, which is more important).

For those interested, follow the link:

  

link


In the case of strings , a PHP line with ordinary functions solves:

$tempo = gmdate('H:i:s', strtotime( $tempo1 ) - strtotime( $tempo2 ) );

See working at IDEONE .

The strtotime() function in this context will turn the time into numeric (in seconds), allowing for conventional mathematical operations.

Then, the function gmdate converts to string again, in the format you put in the question.

Of curiosity, if you only use this part:

strtotime( $tempo1 ) - strtotime( $tempo2 )

The result will be 80, which is the number of seconds between the times of your example.

As the time base of strtotime() is epoch , you can do this to convert a time to "pure" seconds (without the date part):

strtotime( '1970-01-01 '.$horario );

As per comment in another OP duplicate, there is an alternative to using inverted values:

$tempo = gmdate('H:i:s', abs( strtotime( $tempo1 ) - strtotime( $tempo2 ) ) )

In fact it is an example that I did not imagine was necessary, because it is extremely basic, but there it is.

See working at IDEONE .

    
25.04.2016 / 02:36
6

You can also use a library called WallaceMaxters \ Timer to do this:

use WallaceMaxters\Timer\Time;

$t1 = Time::createFromFormat(Time::DEFAULT_FORMAT, $tempo1);

$t2 = Time::createFromFormat(Time::DEFAULT_FORMAT, $tempo2);

$tempo = $t1->diff($t2)->format(Time::DEFAULT_FORMAT);

In the source code of this library, we can see how the values are compared:

public function diff(Time $time, $absolute = true)
{
    $diff = $this->getSeconds() - $time->getSeconds();
    return new self(0, 0, $absolute ? abs($diff) : $diff);
}

I created this library to be able to work with PHP time, especially those that exceed 24 hours.

Important reading:

How to get the format in hours when this exceeds 24?

    
25.04.2016 / 16:06
0

In a very simple way, you can do the following:

<?php
$dteini   = "2018/08/01 12:00:00";
$dtefim   = "2018/08/03 12:59:19";
$dteDiff  = strtotime($dtefim) - strtotime($dteini);
$dte      = new datetime(date('H:i:s'));
$dte      = $dteDiff;
print "Total " . $dte . "<br>";
$total    = $dte;
$horas    = floor($total / 3600);
$minutos  = floor(($total - ($horas * 3600)) / 60);
$segundos = floor($total % 60);
$horas    = str_pad($horas, 2, "0", STR_PAD_LEFT);
$minutos  = str_pad($minutos, 2, "0", STR_PAD_LEFT);
$segundos = str_pad($segundos, 2, "0", STR_PAD_LEFT);
echo $horas . ":" . $minutos . ":" . $segundos;
?>

Result:

Total 176359
48:59:19
    
03.08.2018 / 19:12