This question already has an answer here:
I am trying to find the time difference between two time values in the format H:mm:ss
using PHP.
When I tried with the following code, I'm getting the difference 01:00:20
instead of 00:00:20
. What's wrong with my code?
$start_time = strtotime("0:17:14");
$end_time = strtotime("0:17:34");
$diff = $end_time - $start_time;
echo date('H:i:s', $diff);
</div>
Your $diff
variable is not a timestamp, it's a duration/interval. The date()
function is intended to format timestamps, and won't properly handle intervals like you're expecting.
Instead, try using the DateTime
class to read your timestamps, and turn the difference between them into a DateInterval
using DateTime::diff()
. You can then use DateInterval::format
to get the output you want.
Something like this should work:
$start_time = new DateTime("0:17:14");
$end_time = new DateTime("0:17:34");
$diff = $end_time->diff($start_time);
echo $diff->format('%H:%I:%S');