我需要檢查$ now(在UTC時間)是在某個時間間隔之前,之後還是之間。PHP:檢查日期是否過期(可能是在午夜之後,或者沒有)
因此,如果$ end在午夜之間(例如$start = '18:00'
和$end = '22:00'
)沒有問題。
但經過一些測試,如果$ end是在午夜之後(在我的示例中可以!),我確實「發現」了這可能是一個問題。例如。 $start = '20:00'
和$end = '04:00'
。在這種情況下,$ start將於2017年9月19日發售,最終將於2017年9月20日發售。
這是代碼的第一部分(一些函數來自我自己編寫的SupportDate類)。
/**
* CASE #1 >> NOW can be AFTER start and end time.
* E.g. now == 21.30 and start == 18.00 and end == 21.00
*
* CASE #2 >> NOW can be BEFORE start and end time.
* E.g. Now == 17.00, start == 18, end == 21.00
*
* CASE #3 >> NOW can be BETWEEN start and end time.
* E.g. Now == 19, start == 18, end = 21.00
*/
// CASE #1
if (($support->isExpired($start) === true) && ($support->isExpired($end) === true)) {
echo 'CASE #1 - siamo ben oltre sia l\'inizio che la fine';
}
// CASE #2
if (($support->isExpired($start) === false) && ($support->isExpired($end) === false)) {
echo 'CASE #2 - siamo ben PRIMA sia dell\'inizio che della fine';
}
// CASE #3
if (($support->isExpired($start) === true) && ($support->isExpired($end) === false)) {
echo 'CASE #3 - siamo TRA l\'inizio E la fine';
}
(這是isExpired法)
public function isExpired($date=null,$qty=1,$interval='seconds') {
$now = new \DateTime(null, new \DateTimeZone("UTC"));
$expiry_date = new \DateTime($date, new \DateTimeZone("UTC"));
date_add($expiry_date, date_interval_create_from_date_string($qty.' '.$interval));
if ($now >= $expiry_date) {
return true;
} else {
return false;
}
}
我可以複製3例和應用以前的檢查(僞代碼:如果$開始> $結束否則....)和反轉檢查假的/真的,但我認爲有一個更好的模式來得到我的3例。
謝謝!
您應該查看[carbon](http://carbon.nesbot.com/docs/)和'between'方法。 –
你可以使用'if($ start> $ end)$ end + = 24;'並正常進行。 – inarilo
@inarilo只有當$ now比<23:59時....如果$ now == 23.00,你可以比較$ start = 18:00和$ end = 03.00(你的情況爲27:00)之間。但是如果$ now == 02:00,$現在不在18.00和27:00之間。我希望我很清楚...... – sineverba