计算经过时间的PHP [英] Calculate elapsed time in php
问题描述
您好,我正在尝试计算php中的经过时间.问题不在php中,而是我的数学技能.例如: 时间:11:35:20(hh:mm:ss),现在说当前时间是:12:00:45(hh:mm:ss),那么我公式中的时差给出输出: 1 :-34:25 .实际上应该是:25:25
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;
请帮忙吗?
编辑
对不起,我可能不得不补充,页面每秒刷新一次以显示新的经过时间,因此我必须使用上面的方法.对于无法正确解释,我深表歉意.
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.
推荐答案
这将为您提供从开始到结束之间的秒数.
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);
}
?>
如果不想在小数点后显示数字,只需在secondsToTime()
函数的开头添加round($s);
.
If you don't want to display the numbers after the decimal, just add round($s);
to the beginning of the secondsToTime()
function.
这篇关于计算经过时间的PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!