2014-09-02 66 views
0

我想比較兩次。 但是,首先我想數一次110分鐘。 我做錯了什麼?如何使用php添加和比較兩次

代碼:

$current_time = date("H:i"); 
$match_start = strtotime("H:i", "19:30"); // <- Value from database 
$match_end  = strtotime("+110 minutes", $match_start) 

if($current_time > $match_start && $current_time < $match_end) { 

//Match has started 

} 
+0

有你甚至閱讀[文檔的strtotime(http://php.net/manual/en/function.strtotime.php)?第二個參數應該是時間戳,而不是字符串... – Kleskowy 2014-09-02 13:59:25

回答

1

使用strtotime()

$current_time = strtotime(date("H:i")); // or strtotime(now); 
$match_start = strtotime("14:30"); 
$match_end = strtotime("+110 minutes", $match_start); 

if($current_time > $match_start && $current_time < $match_end) { 
    echo "Match has started"; 
} 

Working demo

1

它可能有一個事實,即你是比較字符串,而不是實際的時間值做。嘗試使用DateTime()這使得這個更清晰。

$current_time = new DateTime(); 
$match_start = new DateTime("19:30"); 
$match_end = (new DateTime("19:30"))->modify("+110 minutes"); 

if($current_time > $match_start && $current_time < $match_end) { 

//Match has started 

} 
0

首先,創建日期時間像這樣(更改datetimezone)另一種解決方案:

$match_start = "19:30"; // <- Value from database 
$current_time = new DateTime('', new DateTimeZone('Europe/Rome')); 

$start = new DateTime($match_start, new DateTimeZone('Europe/Rome')); 
$end = new DateTime($match_start, new DateTimeZone('Europe/Rome')); 

然後加110分鐘結束時間:

$end->add(new DateInterval('PT110M')); 

最後:

if($current_time > $start && $current_time < $end) 
{ 
    //Match has started 
}