我正面临着为时间范围做特殊情况的问题。我有一个函数来决定时间是否在范围内。
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 :(得分:0)
您需要区分$start
小于$end
的情况,反之亦然。
当$start
小于$end
时,您只需测试当前时间是否介于它们之间。
当$start
大于$end
时,表示时间段跨越午夜。在这种情况下,您应该在$start
之前测试当前时间是$end
OR 之后,而不是 AND 。< / p>
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;
}
}
答案 1 :(得分:-1)
假设$start
和$end
已经代表了日期和时间(它们应该是strtotime
将无法正常工作),那么请执行以下操作:
if( time() > strtotime($start) && time() < strtotime($end) ) {
return true
}