Hi All I'm trying to calculate elapsed time in php. The problem is not in php, it's with my mathematical skills. For instance: Time In: 11:35:20 (hh:mm:ss), now say the current time is: 12:00:45 (hh:mm:ss) then the time difference in my formula gives the output: 1:-34:25. It should actually be: 25:25
$d1=getdate(); $hournew=$d1['hours']; $minnew=$d1['minutes']; $secnew=$d1['seconds']; $hourin = $_SESSION['h']; $secin = $_SESSION['s']; $minin = $_SESSION['m']; $h1=$hournew-$hourin; $s1=$secnew-$secin; $m1=$minnew-$minin; if($s1<0) { $s1+=60; } if($s1>=(60-$secin)) { $m1--; } if($m1<0) { $m1++; } echo $h1 . ":" . $m1 . ":" . $s1;
Any help please?
EDIT
Sorry I probably had to add that the page refreshes every second to display the new elapsed time so I have to use my method above. My apologies for not explaining correctly.
Find elapsed time in php using microtime. <? php $s = microtime(true); sleep(1); // 1 seconds $e = microtime(true); $timediff = $e - $s; echo 'Elapsed time (seconds): ' . sprintf('%0.2f', $timediff) .
There are two ways to calculate the total time from the array. Using strtotime() function: The strtotime() function is used to convert string into the time format. This functions returns the time in h:m:s format. Example 1: This example reads the values from the array and converts it into the time format.
php $time = "01:30:00"; list ($hr, $min, $sec) = explode(':',$time); $time = 0; $time = (((int)$hr) * 60 * 60) + (((int)$min) * 60) + ((int)$sec); echo $time; ?>
This will give you the number of seconds between start and end.
<?php // microtime(true) returns the unix timestamp plus milliseconds as a float $starttime = microtime(true); /* do stuff here */ $endtime = microtime(true); $timediff = $endtime - $starttime; ?>
To display it clock-style afterwards, you'd do something like this:
<?php // pass in the number of seconds elapsed to get hours:minutes:seconds returned function secondsToTime($s) { $h = floor($s / 3600); $s -= $h * 3600; $m = floor($s / 60); $s -= $m * 60; return $h.':'.sprintf('%02d', $m).':'.sprintf('%02d', $s); } ?>
If you don't want to display the numbers after the decimal, just add round($s);
to the beginning of the secondsToTime()
function.
Using PHP >= 5.3
you could use DateTime
and its method DateTime::diff()
, which returns a DateInterval
object:
$first = new DateTime( '11:35:20' ); $second = new DateTime( '12:00:45' ); $diff = $first->diff( $second ); echo $diff->format( '%H:%I:%S' ); // -> 00:25:25
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With