2013-01-10 28 views
0

之前,我想这样做在那里:我看一看是时间

$time = time(); 
//Store the time in the dabase 

//Some time later, say three hours this code runs 
// so if your time() was 2pm its now 5pm when this statement 
// is run. 
if($time < 4 hours){ 
    // do something. 
} 

但不知道该怎么做最彻底的方法是。

+3

距离4小时之内?距罗马帝国沦陷4个小时?凌晨4点之前?你的问题需要更多的上下文。 – Jeremy1026

+0

首先你需要赋予'hours'的价值,如'$ hours =“”; – samayo

+0

我认为他的意思是现在4小时前 – poldixd

回答

2

OOP风格

$start = new DateTime; 

// Do something 

if ($start < new DateTime('-4 hours')) { 
    // Do something different 
} 

http://php.net/datetime

非面向对象的方式也很简单

$start = time(); 

// Do something 

if ($start < strtotime('-4 hours')) { 
    // Do something different 
} 

http://php.net/strtotime

1

时间()是要退给你的php时间以秒为单位。当你的代码的第二块运行要()再次检查的时间,所以你应该做这样的事情:

$timeNow = time(); 
if($savedTime < $timeNow-14400){ 
    // do something 
} 

,其中14400是秒4小时(60 * 60 * 4 = = 14400)。当然可能没有理由将time()设置为变量,但以防万一。