Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP中时间范围的特殊情况_Php_Strtotime_Date Range - Fatal编程技术网

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;
    }
}