PHP中时间范围的特殊情况
我正面临一个问题,在时间范围内做一个特例。我有一个函数决定时间是否在范围内PHP中时间范围的特殊情况,php,strtotime,date-range,Php,Strtotime,Date Range,我正面临一个问题,在时间范围内做一个特例。我有一个函数决定时间是否在范围内 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( '
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;
}
}
我如何避免测试在这些特殊情况下失败,并返回true(即使它通过了午夜) 假设
$start
和$end
已经代表了日期和时间(它们应该是或strotime
不会按预期工作),然后执行以下操作:
if(time()>strotime($start)和&time()
您需要区分$start
小于$end
的情况,反之亦然
当$start
小于$end
时,您可以简单地测试当前时间是否介于两者之间
当$start
大于$end
时,表示时间段跨越午夜。在这种情况下,您应该测试当前时间是在$start
之后还是在$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;
}
}
功能检查时间($start,$end){
$start=date('H:i',strottime($start));//例如:上午11:00
$end=date('H:i',strottime($end));//例如:下午2:00
$cur=当前_时间('H:i');
如果($start<$end){
返回$cur>$start&$cur<$end;
}否则{
返回$cur>$start | |$cur<$end;
}
}
使用完整的日期和时间,而不仅仅是小时和分钟。当传递开始和结束变量或在计算过程中?您需要传递它们,并将它们作为日期和时间进行比较。如果我们根据日期进行比较,它仍然会失败,因为午夜之后是不同的日期,只要$start
和$end
表示日期和时间,它就会工作。请看我的回答开始
和结束
不代表日期,只代表时间。所以只要上午11点就可以了
if( time() > strtotime($start) && time() < strtotime($end) ) {
return true
}
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;
}
}