Calculate elapsed time in php
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.
Answer
Solution:
This will give you the number of seconds between start and end.
To display it clock-style afterwards, you'd do something like this:
If you don't want to display the numbers after the decimal, just add
round($s);
to the beginning of thesecondsToTime()
function.Answer
Solution:
Using
PHP >= 5.3
you could useand its method
, which returns a
object:
Answer
Solution:
Keep track of your time using the 'time()' function. You can later convert 'time()' to other formats.
And then you can compare that to another value later on.
Use microtime if you need millisecond detail.
Answer
Solution:
You can implement the solutions shown, but I'm fond of using the phptimer class (or others, this wheel has been invented a few times). The advantage is that you can usually define the timer to be active or not, thereby permitting you to leave the timer calls in your code for later reference without re-keying all the time points.
Answer
Solution:
For high resolution time, try using monotonic clock: hrtime
Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?