Dave
Dave

Reputation: 37

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

Upvotes: 0

Views: 1047

Answers (3)

Shira
Shira

Reputation: 6560

There are multiple problems with the code:

  1. $now - $start_time / 60 doesn't get evaluated the way you are expecting, the division operator has higher precedence than the substraction operator
    • you need to use parentheses to enforce the order, like so: ($now - $start_time) / 60
  2. it doesn't make sense to divide the result by 60 since it's not in minutes, but rather a string in a HHMM format

Can't you store the login times as timestamps or datetime columns instead? It would be much easier to work with.

Anyway, to do do this properly (in this case), I'd use the DateTime class:

$start_time = "0900";

$start = DateTime::createFromFormat('Hi', $start_time);
$now = new DateTime('NOW');
$diff = $start->diff($now);
$total_hours = ($diff->h * 3600 + $diff->i * 60 + $diff->s) / 3600 * ($diff->invert ? -1 : 1);

var_dump($total_hours);

This code prints the number of hours (as a float) since the $start_time. If will be negative if NOW is before the $start_time.

If it's 14:51:44, the result will be:

float(5.8622222222222)

If it's 05:20:31, the result will be:

float(-3.6580555555556)

Upvotes: 1

postrel
postrel

Reputation: 134

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');

Upvotes: 0

Mischa
Mischa

Reputation: 43298

I would use a Unix timestamp (number of seconds since 1/1/1970) to store the last login. Subtract the last login timestamp from the current timestamp and divide that by 3600 seconds to get the number of hours.

$total_hours = (time() - $last_login) / 3600;

Upvotes: 1

Related Questions