Time is confusing... How can one calculate the time elapsed from PM to AM in php?
For example 22:00:00 (10pm)
to 02:00:00 (02am)
should give 04 hours
elapsed. Instead my code returns -08 hours
function hours_elapsed()
{
$timestart = strtotime("22:00:00");
$timestop = strtotime("02:00:00");
$time_diff = $timestop - $timestart; //time difference
return gmdate("h", $total_hours);
}
It's clear that the code calculates in 24 hour format so of course it returns -08
but how is it possible to get time elapsed without 24 hour constraint.. when it passes the midnight mark?
-8
hours is 4
hours. Just add 12
if the number is negative:
$time_diff = $timestop - $timestart; //time difference
if ($time_diff < 0) {
$time_diff += 12;
}
This won't help you, however, if your dates are more than one day apart. You need to specify the date as well (as in the day of the month) to tell PHP that those times are different.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With