$start_time = '10:36:23';
$end_time = '10:36:26';
$v = strtotime($end_time) - strtotime($start_time);
echo date("h:i:s", $v);
Result should be 00:00:03. But is showing 12:00:03.
How can i resolve this?
Lowercase h gives you the hour in 12-hour format. So an hour of zero is after midnight which is 12 AM. If you use uppercase H it will display as you want.
echo date("H:i:s", $v);
Your difference is not actually a time, it is a time span.
The error in where you are echoing out ur date change it to this echo date('H:i:s', $v);
with an uppercase H
The difference calculation is correct, and $v == 3
, but you are then using date
to format it as a time.
This will output the local time equivalent of 1970-01-01 00:00:03 +0000
, which could vary based on local timezone (and possibly daylight savings time).
If you want to format a difference in such a way, you could use gmdate
(which will show correctly regardless of local timezone) and a 24-hour clock:
echo gmdate("H:i:s", $v);
You could also use DateTime
:
$start_time = new DateTime('10:36:23', new DateTimeZone('UTC'));
$end_time = new DateTime('10:36:26', new DateTimeZone('UTC'));
$diff = $end_time->diff($start_time);
echo $diff->format("%H:%I:%S");
This is just a tip.
You can also use the datetime object to calculate the difference between two dates:
$start_time = new DateTime('10:36:23');
$end_time = new DateTime('10:36:26');
$diff = $start_time->diff($end_time);
print_r($diff);
Result:
DateInterval Object
(
[y] => 0
[m] => 0
[d] => 0
[h] => 0
[i] => 0
[s] => 3
[invert] => 0
[days] => 0
)
Where the 's' stands for the number of seconds.