PHP check if time falls within range, questioning common solution

ⅰ亾dé卋堺 提交于 2019-12-07 16:51:59

问题


I have to check if the current daytime falls in a specific range. I looked up the internet and found several similar solutions like this one:

$now = date("His");//or date("H:i:s")

$start = '130000';//or '13:00:00'
$end = '170000';//or '17:00:00'

if($now >= $start && $now <= $end){
echo "Time in between";
}
else{
echo "Time outside constraints";
}

If both conditions have to be true, how can this bis achieved when we assume that $start is 06:00:00 and $end is 02:00:00.

If we make the assumption that it is 01:00:00, in this case the first condition can't be true.

Has anybody an idea to handle this problem differently?

Thanks!


回答1:


Naturally, you'd have to account for date in your comparisons.

<?php

$start = strtotime('2014-11-17 06:00:00');
$end = strtotime('2014-11-18 02:00:00');

if(time() >= $start && time() <= $end) {
  // ok
} else {
  // not ok
}



回答2:


If you need to check whether or not the time frame rolls over midnight

    function isWithinTimeRange($start, $end){

        $now = date("His");

        // time frame rolls over midnight
        if($start > $end) {

            // if current time is past start time or before end time

            if($now >= $start || $now < $end){
                return true;
            }
        }

        // else time frame is within same day check if we are between start and end

        else if ($now >= $start && $now <= $end) {
            return true;
        }

        return false;
    }

You can then get whether or not you are within that time frame by

echo isWithinTimeRange(130000, 170000);



回答3:


date_default_timezone_set("Asia/Colombo");
            $nowDate = date("Y-m-d h:i:sa");
            //echo '<br>' . $nowDate;
            $start = '21:39:35';
            $end   = '25:39:35';
            $time = date("H:i:s", strtotime($nowDate));
            $this->isWithInTime($start, $end, $time);


 function isWithInTime($start,$end,$time) {

            if (($time >= $start )&& ($time <= $end)) {
               // echo 'OK';
                return TRUE;
            } else {
                //echo 'Not OK';
                return FALSE;
            }

}


来源:https://stackoverflow.com/questions/26978521/php-check-if-time-falls-within-range-questioning-common-solution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!