如何计算PHP的时差?
我必须计算日期时间差,如何在PHP中做到这一点?我需要确切的小时,分钟和秒。有人有这方面的脚本吗?
使用 PHP 的 DateTime 类的 diff() 方法,如下所示:-
$lastWeek = new DateTime('last thursday');
$now = new DateTime();
var_dump($now->diff($lastWeek, true));
这将为您提供一个 DateInterval 对象:-
object(DateInterval)[48]
public 'y' => int 0
public 'm' => int 0
public 'd' => int 2
public 'h' => int 11
public 'i' => int 34
public 's' => int 41
public 'invert' => int 0
public 'days' => int 2
从中检索所需的值是微不足道的。
这应该有效,只需将时间差异中的时间替换为任务开始的时间以及当前时间或任务结束的时间即可。对于连续计数器,开始时间将存储在数据库中,对于任务的已用时间,结束时间也将存储在数据库中
function timeDiff($firstTime,$lastTime){
// convert to unix timestamps
$firstTime=strtotime($firstTime);
$lastTime=strtotime($lastTime);
// perform subtraction to get the difference (in seconds) between times
$timeDiff=$lastTime-$firstTime;
// return the difference
return $timeDiff;
}
//Usage :
$difference = timeDiff("2002-03-16 10:00:00",date("Y-m-d H:i:s"));
$years = abs(floor($difference / 31536000));
$days = abs(floor(($difference-($years * 31536000))/86400));
$hours = abs(floor(($difference-($years * 31536000)-($days * 86400))/3600));
$mins = abs(floor(($difference-($years * 31536000)-($days * 86400)-($hours * 3600))/60));#floor($difference / 60);
echo "<p>Time Passed: " . $years . " Years, " . $days . " Days, " . $hours . " Hours, " . $mins . " Minutes.</p>";