如何计算PHP的时差?

php*_*ner 12 php date

我必须计算日期时间差,在PHP中如何做到这一点?我需要精确的小时,​​分​​钟和秒.有人有脚本吗?

vas*_*ite 26

使用PHP的DateTime类diff()方法,如下所示: -

$lastWeek = new DateTime('last thursday');
$now = new DateTime();
var_dump($now->diff($lastWeek, true));
Run Code Online (Sandbox Code Playgroud)

这将为您提供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
Run Code Online (Sandbox Code Playgroud)

从中检索您想要的值是微不足道的.


小智 9

检查一下..这应该有效

<?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");

?> 
Run Code Online (Sandbox Code Playgroud)


Jam*_*ams 7

这应该工作,只需将时间差异中的时间替换为任务开始的时间和当前时间或任务结束的时间.对于连续计数器,开始时间将存储在数据库中,或者对于任务的已用时间也将存储在结束时间中

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>";
Run Code Online (Sandbox Code Playgroud)