Can't subtract two hours in php

137 views Asked by At

Im trying to subtract tow hours, this is my code (crono() subtracts two hours):

include("classes/Functions.php");//contains crono()
include("classes/database.php");//database connection

$selectActual = "SELECT * from InfActual WHERE state='on'";
$resultActual = $conn->query($selectActual);
if ($resultActual->num_rows > 0) {
    while ($rowActual = $resultActual->fetch_assoc()) {
        $horaIni = $rowActual['horaIni'];
        $actual = date("h:i:s");
        echo "horaini: ".$horaIni." actual: ".$actual."<br>";
        echo "subtract: ".crono($hora, $actual)."<br>";
    }
}

And this is the result

horaini: 05:41:25 actual: 05:53:43
subtract: 05:53:43

I think the problem is that $rowActual['horaIni'] is not in the same format as $actual (I'm not totally sure), I don't know how to solve this.

[Solved]

echo "subtract: ".crono($horaIni, $actual)."<br>";
4

There are 4 answers

0
Safira On BEST ANSWER

Sorry, I'm so stupid, I'm not using $horaIni in crono() function. So sorry.

0
tempcke On

Why not do it in sql?

SELECT *, horaini - INTERVAL 2 HOUR AS horaini2

In php you would use strtotime()

date('H:i:s', strtotime($rowActual['horaIni']) - 60 * 60 * 2);
0
OllyBarca On

Use strtotime

echo date("h:i:s", strtotime($actual."-2 hour"));
0
Rash On
<?php

$oldDate = date('Y-m-d h:i:sa');
$newDate = date('Y-m-d h:i:sa', strtotime('-2 hours'));

echo $oldDate;
echo "<BR>";
echo $newDate;

?>

This should do the trick