Calculate elapsed time in php

2019-01-22 12:50发布

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.

标签: php time
4条回答
姐就是有狂的资本
2楼-- · 2019-01-22 13:00

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
查看更多
做自己的国王
3楼-- · 2019-01-22 13:13

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.

查看更多
爷的心禁止访问
4楼-- · 2019-01-22 13:16

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.

查看更多
Fickle 薄情
5楼-- · 2019-01-22 13:22

Keep track of your time using the 'time()' function. You can later convert 'time()' to other formats.

$_SESSION['start_time'] = time();

$end_time = time();

$end_time - $_SESSION['start_time'] = 65 seconds (divide by 60 to get minutes)

And then you can compare that to another value later on.

Use microtime if you need millisecond detail.

查看更多
登录 后发表回答