2011-12-12 129 views
25

如果當前時間是當天下午2點之前,我需要檢查PHP。PHP檢查當前時間是否在指定時間之前

我和strtotime約會前的0.00每一天的時間就會被複位做到了這一點,但是這一次,它是隻用一次,所以很明顯,且布爾將復位從falsetrue

if (current_time < 2pm) { 
    // do this 
} 
+1

這甚至不是有效的PHP。什麼是'current_time'? – KingCrunch

+6

@KingCrunch我認爲這是僞代碼,而不是實際的代碼。 :-) –

+1

我知道這不是有效的PHP,我只是舉了一個邏輯例子。 –

回答

58
if (date('H') < 14) { 
    $pre2pm = true; 
} 

有關日期函數請see the PHP manual更多信息。我已經使用了以下時間格式:

H成小時(00到23)= 24小時格式

+0

不需要幾分鐘的好處。頭腦鏈接到「H」的文檔? –

+0

http://uk.php.net/manual/en/function.date.php列出格式化日期的所有不同方式。思考它可能會更清晰,因爲它不包含小時只有1位數的前導0,儘管PHP並不挑剔足以讓if語句的結果產生影響。 – Tom

+0

歡呼編輯Treffynnon,有用的零零碎碎。 – Tom

0

if(time() < mktime(14, 0, 0, date("n"), date("j"), date("Y"))) { 

// do this 

} 
4

使用24小時時間儘量避開這個問題,像這樣:

$time = 1400; 
$current_time = (int) date('Hi'); 
if($current_time < $time) { 
    // do stuff 
} 

所以2PM等同於14:00 24小時時間。如果我們從時間中刪除冒號,那麼我們可以在比較中將其評估爲整數。

有關日期功能的更多信息,請致電see the PHP manual。我已經使用以下時間格式化:

H成小時(00〜23)

I =用前導零(00〜59)分

18

菜系= 24小時格式:

if(date("Hi") < "1400") { 
} 

參見:http://php.net/manual/en/function.date.php

H 24-hour format of an hour with leading zeros 00 through 23 
i Minutes with leading zeros      00 to 59 
+0

嘿,正在瘋狂地試圖讀取​​與$前面。沒有幫助,它說'嗨'^^ – JohnP

+0

爲什麼不鏈接到實際的PHP手冊? –

+0

@JaredFarrish:Google是我的oracle :)現在修復了 –

11

你可以只通過在時間

if (time() < strtotime('2 pm')) { 
    //not yet 2 pm 
} 

還是在日期傳遞明確以及

if (time() < strtotime('2 pm ' . date('d-m-Y'))) { 
    //not yet 2 pm 
} 
+0

+1;修正拼寫錯誤和向後比較。 –

1

你還沒有告訴我們您正在運行的PHP版本,雖然,假設它是PHP 5.2.2+比你應該能夠做到像:

$now = new DateTime(); 
$twoPm = new DateTime(); 
$twoPm->setTime(14,0); // 2:00 PM 

然後就問:

if ($now < $twoPm){ // such comparison exists in PHP >= 5.2.2 
    // do this 
} 

否則,如果你使用的舊版本的一個(比如說5.0),這應該做的伎倆(和很多simplier):

$now = time(); 
$twoPm = mktime(14); // first argument is HOUR 

if ($now < $twoPm){ 
    // do this 
} 
0

此功能將檢查它是否小時之間EST被接受2個參數,帶小時和上午/下午的數組...

/** 
    * Check if between hours array(12,'pm'), array(2,'pm') 
    */ 
    function is_between_hours($h1 = array(), $h2 = array()) 
    { 
     date_default_timezone_set('US/Eastern'); 
     $est_hour = date('H'); 

     $h1 = ($h1[1] == 'am') ? $h1[0] : $h1[0]+12; 
     $h1 = ($h1 === 24) ? 12 : $h1; 

     $h2 = ($h2[1] == 'am') ? $h2[0] : $h2[0]+12; 
     $h2 = ($h2 === 24) ? 12 : $h2; 

     if ($est_hour >= $h1 && $est_hour <= ($h2-1)) 
      return true; 

     return false; 
    } 
0

使用time()date()strtotime()功能:

if(time() > strtotime(date('Y-m-d').' 14:00') { 
    //... 
} 
0

如果您要檢查的時間是否是下午2:30之前,你可以試試下面的代碼段。

if (date('H') < 14.30) { 
    $pre2pm = true; 
}else{ 
    $pre2pm = false; 
} 
相關問題