Karem
Karem

Reputation: 18103

Does not get the time difference correct in PHP

$time1 = "01:00";
$time2 = "04:55";
list($hours1, $minutes1) = explode(':', $time1);
$startTimestamp = mktime($hours1, $minutes1);

list($hours2, $minutes2) = explode(':', $time2);
$endTimestamp = mktime($hours2, $minutes2);

$seconds = $endTimestamp - $startTimestamp;
$minutes = ($seconds / 60) % 60;
$hours = round($seconds / (60 * 60));

echo $hours.':'.$minutes;
exit;

Outputs 4:55, should be 3:55 ?

Whats wrong here? If it is 01:00 and 02:00, it works fine, but not with the above?

Upvotes: 1

Views: 53

Answers (4)

Kermit
Kermit

Reputation: 34055

You can also save yourself some time by using strtotime:

$time1 = strtotime("01:00");
$time2 = strtotime("04:55");

$seconds = $time2-$time1;
$minutes = ($seconds / 60) % 60;
$hours = floor($seconds / (60 * 60));

echo $hours.':'.$minutes;

As mentioned, using floor will produce the result you need:

Result

3:55

Upvotes: 0

Baba
Baba

Reputation: 95101

Too many calculations when PHP can do it for you with also reducing possibility of error

$time1 = Datetime::createFromFormat("h:i", "01:00");
$time2 = Datetime::createFromFormat("h:i", "04:55");

$diff = $time1->diff($time2);
var_dump($diff->format("%h %i"));

Output

string '3:55' (length=4)

Upvotes: 0

xdazz
xdazz

Reputation: 160833

Or just cast to integer.

$hours = (int) ($seconds / (60 * 60));

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

Use floor instead of round...

Upvotes: 6

Related Questions