Nrc
Nrc

Reputation: 9797

From string to milliseconds and back

I want to make some operations with two hours stored in vars. I first convert to milliseconds make the operations and then convert back to something readable. It seems to work but the final number is not right. In this example it gives me 1:30:00 of difference. Can someone explain why?

// I have two hours that come from a MySql database and I store in a var:
$start= "16:00:00";
$end= "16:30:00";

// I convert to milliseconds and rest:
$startMili = strtotime($start);
$endMili = strtotime($end);
$dif = $endMili - $startMili ;

// convert to something readable:
echo "<br><br> diference: ";
$readable = date("H:i:s", $dif);
echo $readable;

Upvotes: 0

Views: 63

Answers (1)

Perry
Perry

Reputation: 11710

You can use also DateTime instead of strtotime

see below the example

$datetime1 = new DateTime($start, new DateTimeZone('Europe/Amsterdam'));
$datetime2 = new DateTime($end, new DateTimeZone('Europe/Amsterdam'));
$interval = $datetime1->diff($datetime2);
echo $interval->format('%H:%i:%s');

Upvotes: 1

Related Questions