Forum Moderators: coopster

Message Too Old, No Replies

How to calculate the time difference in php?

         

An156

5:30 pm on Apr 9, 2009 (gmt 0)

10+ Year Member



Hi All!
i need to calculate time difference.
i have
$t1='09:00:00';
and $t2='13:10:32';

then how can i show the difference in HH:MM:SS format?

Please help!

Thanks in advance :)

CyBerAliEn

6:59 pm on Apr 9, 2009 (gmt 0)

10+ Year Member



What I would do...

Convert the times to seconds. Find the difference in seconds, then use this to build back up to the difference (in hours/mins/secs). ie:


function getMyTimeDiff($t1,$t2)
{
$a1 = explode(":",$t1);
$a2 = explode(":",$t2);
$time1 = (($a1[0]*60*60)+($a1[1]*60)+($a1[2]));
$time2 = (($a2[0]*60*60)+($a2[1]*60)+($a2[2]));
$diff = abs($time1-$time2);
$hours = floor($diff/(60*60));
$mins = floor(($diff-($hours*60*60))/(60));
$secs = floor(($diff-(($hours*60*60)+($mins*60))));
$result = $hours.":".$mins.":".$secs;
return $result;
}
$mytime1 = "14:05:08";
$mytime2 = "03:22:54";
$cool = getMyTimeDiff($mytime1,$mytime2);

I would test the code, as I just quickly typed it up, and it may not work. lol. But you should get the general idea from it. (note, this is not the exact/best approach if you want to also account for days/months/etc)

[edited by: CyBerAliEn at 7:01 pm (utc) on April 9, 2009]

[edited by: eelixduppy at 10:43 pm (utc) on April 9, 2009]
[edit reason] fixed formatting [/edit]

eeek

7:16 pm on Apr 9, 2009 (gmt 0)