如何计算从秒发出的请求2小时

时间:2015-06-30 11:52:19

标签: php

我的服务器时间是GMT,因此我将其转换为亚洲/吉隆坡时间。我需要计算当前时间与请求时间之间的时差。发出的时间请求存储在数据库中,并在$reset_req变量中检索。

$reset_req="2015-06-30 11:30:23";   

$timezone_offset = +8; // us central time (gmt-6) for me

if(isset($reset_req)){
 $request_date2 = strtotime($reset_req)+$timezone_offset*60*60;
}
echo "current time= ".strtotime(time());
echo"<br/>";
echo "time req made=".strtotime($request_date2);
echo"<br/>";
  $timediff = strtotime(time()) - strtotime($request_date2); // in seconds

if($timediff < 2 hours)//how to calculate 2 hours here
{
//do something
}

4 个答案:

答案 0 :(得分:1)

每个人都已经说过如何计算2小时(2 * 3600秒)。但他们没有告诉你的是你不能这样做:strtotime(time()); time();已经为你提供了一个Unix时间戳,所以你不能将它转换两次。

您的代码看起来应该更像

<?php

$reset_req = "2015-06-30 11:30:23";   

$timezone_offset = +8; // us central time (gmt-6) for me

if(isset($reset_req)){
      $request_date2 = strtotime($reset_req)+$timezone_offset*60*60;
      $current = time();
} else {
      echo '$reset_req was not set';
      exit;
}

echo "current time= " . $current . "<br />";
echo "time req made=" . $request_date2 . "<br />";

$timediff = $current - $request_date2; // in seconds

if($timediff < (2*3600))//how to calculate 2 hours here
{
    echo "less than 7200 sec have past since $request_date2. Past: $timediff seconds";    
}else{
    echo "more than 7200 sec have past since $request_date2. Past: $timediff seconds";   
}

?>

答案 1 :(得分:0)

$hour = 3600; //an hour has 3600 seconds
if($timediff < 2 * $hour )
{
//do something
}

答案 2 :(得分:0)

$ timediff是几秒钟。因此,您必须将其转换为小时或将2小时转换为秒,然后需要进行比较,如下所示:

替换

if($timediff < 2 hours)//how to calculate 2 hours here
{
 //do something
}

if($timediff < (2*3600))//how to calculate 2 hours here
{
 //do something
}

答案 3 :(得分:0)

Try this

<?php

$reset_req = "2015-06-30 11:30:23"; 

//set default timezone here
date_default_timezone_set("Asia/Kuala_Lumpur");

$request_date2 = '';

if(isset($reset_req))
{
    $request_date2 = strtotime($reset_req);
}

echo "Current time = ".time();
echo"<br/>";
echo "Time req made =".$request_date2;
echo"<br/>";

$timediff = time() - $request_date2; // in seconds
echo "<br>Time Differnce : ".$timediff;

//how to calculate 2 hours here
if($timediff < 2*3600)
{
    //do something
}

?>