2013-01-10 32 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()設置爲變量,但以防萬一。