Return the difference between two (dates and time

2019-09-24 16:36发布

i tried most of what is available on stack overflow but none seem to work.

any way i am trying to compare two (date and time formats). and calculate whether their difference is within 5 seconds of each other

the first date is the current date:

$today   = date("Y-m-d H:i:s");

the second date is taken from mysql database:

$result = mysql_query("SELECT * FROM BUS_DATA where BusRegID = 'bus'") or die(mysql_error());
$row     = mysql_fetch_array($result);
$update_date  = $row["update_date"];

the answer should be segmented into years , month , days , hours , minutes ,and seconds portions.

I am running PHP Version 5.3.3

Edit: most answers give result in time frame only , I want to check whether the date matches , then compare if the time of the day is within 5 seconds , than you guys in advance :)

3条回答
干净又极端
2楼-- · 2019-09-24 17:00

use strtotime, it's understands almost any date formats:

$timeDiff = abs(strtotime($today) - strtotime($update_date));

this gives you the difference between dates in seconds.

查看更多
Emotional °昔
3楼-- · 2019-09-24 17:00

If you want to know whether it's within 5 seconds then use Timestamps, makes it into a simple int calculation.

$now = time();
$test = strtotime($update_date);
if($now - $test > 5) {
    //NOT WITHIN 5 SECONDS
}
查看更多
疯言疯语
4楼-- · 2019-09-24 17:15
Try this
function getTimes($t1, $t2)
{
$timeFirst  = strtotime($t1);
$timeSecond = strtotime($t2);
$differenceInSeconds = $timeSecond - $timeFirst;
$h=0;
$m  = floor($differenceInSeconds / 60);
$s  = $differenceInSeconds % 60;
if ($m>=60)
{
  $h = floor($m / 60);
  $m = $m % 60;
}
$tim = $h.':'.$m.':'.$s;
return $tim;
}
it will return difference time in hours:min:sec
查看更多
登录 后发表回答