0

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);
John Ellmore
  • 2,209
  • 1
  • 10
  • 22
Psl
  • 3,830
  • 16
  • 46
  • 84
  • Exact Duplicate of: https://stackoverflow.com/q/22475091/2943403 – mickmackusa Nov 09 '17 at 03:49
  • @mickmackusa you can add extra duplicates to the list via the ["edit"](https://stackoverflow.com/questions/originals/47193446/edit) link :) – Phil Nov 09 '17 at 03:50
  • @Phil I've never done that before / don't know how to do that / don't see what you are suggesting. Do I have this ability? Do I need a gold PHP badge or something? – mickmackusa Nov 09 '17 at 03:52
  • @mickmackusa oh, must be a higher-rep privilege. I've added your link into the list at the top – Phil Nov 09 '17 at 03:55
  • @Phil Good on ya. I guess I'll need to to wait until I am more grown up to edit the list. Will this be insta-deleted as exact duplicate? – mickmackusa Nov 09 '17 at 03:56

1 Answers1

1

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');
John Ellmore
  • 2,209
  • 1
  • 10
  • 22