Farzad Salimi Jazi Farzad Salimi Jazi - 10 months ago 57
PHP Question

hh:mm:ss difference return wrong answer in php

I am using this code to calculate the time period. In fact, I want the period between two HH:MM:SS moment and have a result in HH:MM:SS format.

$time1 = strtotime('00:00:00');
$time2 = strtotime('00:00:07');
$diff = $time2 - $time1;
$diff = date('H:i:s', $diff);

I'm expecting
but I get
. What could be the problem?

Irvin run here, and get right answer but I run the same code on my local machine and wrong!!
Is it timezone or maybe some configuration effect the result?!

Answer Source

Please stop using strtotime and date functions. Use the DateTime class.

And if you would have searched better, finding difference for two dates has already been all over SO. For instance, my answer here. Slightly changed it would look like:

$create_time = "00:00:00";

$dtCurrent = DateTime::createFromFormat('H:i:s', $current_time);
$dtCreate = DateTime::createFromFormat('H:i:s', $create_time);
$diff = $dtCurrent->diff($dtCreate);

echo $diff->format("%H:%I:%S"); // to get HH:MM:SS format

This returns 00:00:07 See DateInterval::format for more formatting details.