2012-09-23 80 views
2

因此可以將時間與<,>等進行比較,但與strtotime一起使用時,會得到unix時間戳,因此您無法比較與日期無關的時間。比較不帶日期的日期

我希望做的是能夠表達這樣的:

$reference_time = "2010-01-01 18:00:00"; 
print strtotime("19:00:00") > strtotime($reference_time); 
print strtotime("16:00:00") > strtotime($reference_time); 

但我想第二個表達式返回false(因爲忽略了日期,時間短)。什麼是最簡單的方法來做到這一點? (最好不要拆分字符串)

+0

這已經被問過,請使用搜索功能。 – hakre

+0

@hakra:我確實看過,但無法找到任何東西。這似乎是一個共同的需要... – amindfv

+0

問題是(重複)日期/時間問題的數量是很大,你甚至無法找到現在快速正確的東西。但是我也發現發佈答案比搜索更容易:/ – hakre

回答

3

strtotime也有第二個參數。嘗試:

$reference_time = "2010-01-01 18:00:00"; 
$absolute = strtotime($reference_time); 

print strtotime("19:00:00", $absolute) > $absolute; 
print strtotime("16:00:00", $absolute) > $absolute; 

演示:http://codepad.org/uG4bsxTH

+0

美麗,謝謝! – amindfv

1

您可以將每個Unix時間戳的模數相對於86400(一天中的秒數)。

http://php.net/manual/en/language.operators.arithmetic.php

+1

這不是用UNIX時間戳工作的方式。您只能計算秒數,但一天中的秒數*會變化*。 – hakre

+0

還鏈接PHP的操作碼頁面?爲什麼這應該是有用的? – hakre

+0

你是絕對正確的,快樂。我的回答有點聰明,而且錯了。 – jrajav

0

你可以這樣做:

print strtotime("19:00:00") > strtotime(explode(' ',$reference_time)[1]); 
print strtotime("16:00:00") > strtotime(explode(' ',$reference_time)[1]); 

你需要PHP 5.4作爲對的最小值上面的代碼工作。