计算php中经过的时间
大家好,我正在尝试计算 php 中的经过时间。问题不在于 php,而在于我的数学技能。例如: 时间:11:35:20 (hh:mm:ss),现在说当前时间是:12:00:45 (hh:mm:ss) 那么我的公式中的时间差给出输出:1 :-34:25。实际上应该是: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;
有什么帮助吗?
编辑
抱歉,我可能必须添加页面每秒刷新一次以显示新的经过时间,因此我必须使用上面的方法。我很抱歉没有正确解释。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这将为您提供开始和结束之间的秒数。
要随后以时钟样式显示它,您可以执行以下操作:
如果您不想显示小数点后的数字,只需将
round($s);
添加到开头即可secondsToTime()
函数。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.使用
PHP >= 5.3
您可以使用DateTime
及其方法DateTime::diff()
,返回一个DateInterval
对象:Using
PHP >= 5.3
you could useDateTime
and its methodDateTime::diff()
, which returns aDateInterval
object:使用“time()”函数跟踪您的时间。
您稍后可以将“time()”转换为其他格式。
然后您可以稍后将其与另一个值进行比较。
如果您需要毫秒细节,请使用 microtime。
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.
对于高分辨率时间,请尝试使用单调时钟: hrtime
CLOCK_REALTIME 和 CLOCK_MONOTONIC 之间的区别?
For high resolution time, try using monotonic clock: hrtime
Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?
您可以实现所示的解决方案,但我喜欢使用 phptimer 类(或其他,这个轮子已经被发明了几次)。优点是您通常可以将计时器定义为活动或不活动,从而允许您将计时器调用保留在代码中以供以后参考,而无需重新键入所有时间点。
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.