Dave Dave - 5 months ago 8
PHP Question

How many hours have passed

This question has been asked in a one form or another but people have always been after an answer to how many days / hours / minutes / seconds have passed. My question is different and yes I have reviewed other questions. I am working on a coding task that part of requires me to work out how many hours (just hours not mins/secs) have passed since the last sign in. So if an employee signs in at say 9am and then leaves early at 4:30pm that would be 7.5 hours which I'd then use a SQL statement to store in a table.

How would I go about calculating the total hours passed? I have tried the following but I'm really not good with these things:-

$start_time = "0900";
$now = date("Hi");
$total_hours = $now - $start_time / 60;


As I said this just gave me 524 but now idea if that was right or if that needs to be converted by division or something.

Please help, thanks in advance

Answer

In your code you initialize two string variables that are converted to integers by PHP when you make a subtraction.

You could use the DateTime class to get the time difference in hours.

$timeZone = new DateTimeZone('UTC');
$start = DateTime::createFromFormat('Hi', '0900', $timeZone);
$end = new DateTime('now', $timeZone);
$interval = $start->diff($end);
echo $interval->format('%h hours');