在PHP

2017-04-07 22 views
1

时间范围特殊情况下,我面临着这样的时间范围内的特殊情况的问题。我有一个决定时间是否在范围内的功能。在PHP

function check_time($start, $end){ 
    $start = date('H:i', strtotime($start)); // ex: 11:00 AM 
    $end = date('H:i', strtotime($end)); // ex: 2:00 PM 
    // check the range 
    if (current_time('H:i') > $start && current_time('H:i') < $end) { 
     return true; 
    } 
} 

这适用于不同的情况,但如果结束时间通过午夜到第二天,它将失败。

for example, assume the current time is 3:00 PM 
6:00 AM - 10:00 PM // true 
1:00 PM - 9:00 PM // true 
2:00 PM - 1:00 AM // false // should be true 
2:00 PM - 2:00 AM // false // should be true 

如何避免测试在这些特殊情况下失败,并且即使经过午夜也返回true?

+0

使用完整的日期和时间而不是只是小时和分钟。 – Cfreak

+0

何时传递开始和结束变量或在计算过程中? – user7834963

+0

你需要在通过他们和他们比较日期和时间。 – Cfreak

回答

0

你需要区分的情况下,$start小于$end反之亦然。

$start小于$end时,您可以简单地测试当前时间是否在它们之间。

$start大于$end更大,则意味着thhe时间段杂交午夜。在这种情况下,你应该测试,如果当前时间后$startOR$end之前,而不是

function check_time($start, $end){ 
    $start = date('H:i', strtotime($start)); // ex: 11:00 AM 
    $end = date('H:i', strtotime($end)); // ex: 2:00 PM 
    $cur = current_time('H:i'); 
    if ($start < $end) { 
     return $cur > $start && $cur < $end; 
    } else { 
     return $cur > $start || $cur < $end; 
    } 
} 
+0

感谢您的解释 – user7834963

-1

假设$start$end已经代表了日期和时间(他们应该或预期strtotime将无法​​正常工作),然后执行:

if(time() > strtotime($start) && time() < strtotime($end)) { 
    return true 
} 
+0

'start'和'end'并不代表日期,但只是时间的。所以只是'11:00 AM' – user7834963