【发布时间】:2011-02-24 14:35:16
【问题描述】:
我必须计算日期时间差,如何在 PHP 中做到这一点?我需要准确的小时、分钟和秒。有人有那个脚本吗?
【问题讨论】:
我必须计算日期时间差,如何在 PHP 中做到这一点?我需要准确的小时、分钟和秒。有人有那个脚本吗?
【问题讨论】:
像这样使用 PHP 的 DateTime class 的 diff() method:-
$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
从中检索您想要的值很简单。
【讨论】:
检查这个..这应该可以工作
<?php
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 :
echo timeDiff("2002-04-16 10:00:00","2002-03-16 18:56:32");
?>
【讨论】:
这应该可以,只需将时间差异中的时间替换为任务开始的时间和当前时间或任务结束的时间。对于连续计数器,开始时间将存储在数据库中,或者对于任务的经过时间,结束时间也将存储在数据库中
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>";
【讨论】:
对于类似的事情,请使用内置的 int time() 函数。
time(); 的值类似于1274467343
这是开始的秒数$erlierTime。time()分配给后者
停止你想要的时间,让我们
叫它$latterTime
所以现在你有像$erlierTime 和$latterTime 这样的东西。
不用$latterTime - $erlierTime 以秒为单位计算差异,然后进行除法以获取经过的分钟数、经过的小时数等。
为了让我或任何人给你一个完整的脚本,你需要告诉我们你的环境是什么样的,你在使用什么 mysql、sqlite 等...还需要知道这个计时器是如何触发的.
【讨论】:
您必须通过 strtotime 转换您的开始日期时间和结束时间。
然后从结束时间中减去开始时间。
然后将差异传递给您需要的日期或时间格式...
所以你会得到两个日期之间的确切差异。
【讨论】: