2012-07-26 120 views
2

我的變量,$current$row['start']是在2012-07-24 18:00:00如何在PHP中有條件地編寫此代碼?

格式該怎麼寫以下?

if ($row['start'] - $current < 2 hours) echo 'starts soon'

此外,有沒有辦法把它與下面的結合?

<?php echo ($current > $row['start']) ? 'Started' : 'Starts'; ?> 

回答

2

您可以使用strtotime()那些日期時間字符串轉換成時間戳,然後可以添加和海誓山盟減去。

$diff = strtotime($row['start']) - strtotime($current); 
if ($diff < 7200) { 
    echo 'Starts soon'; 
} else if ($diff <= 0) { 
    echo 'Started'; 
} else { 
    echo 'Starts'; 
} 
+0

感謝你爲這個。我想如果沒有將它們轉換爲時間戳,沒有辦法做到這一點? – 2012-07-26 00:53:07

+0

不,您可以使用'>','<'和'=='來比較日期字符串,但不能像這樣分辨實際的時間差異。 [DateTime :: diff()](http://www.php.net/manual/en/datetime.diff.php)也可以給你不同之處,但內部值無論如何都會轉換爲時間戳。 – drew010 2012-07-26 01:01:30

0

我建議在幾秒鐘內工作(自新紀元),其中的strtotime()是偉大的:

define("SOON_THRESHOLD", 2*60*60); // 7200 seconds == 2 hours 
$start_time = strtotime($row['start']); 
$current_time = strtotime($current); 
$seconds_til_start = $start_time - $current_time; 

if($seconds_til_start < SOON_THRESHOLD) { 
    ... 
}