PHP Check if time is between two times regardless

2019-01-15 04:14发布

I'm writing a script were I have to check if a time range is between two times, regardless of the date.

For example, I have this two dates:

$from = 23:00
$till = 07:00

I have the following time to check:

$checkFrom = 05:50 
$checkTill = 08:00

I need to create script that will return true if one f the check values is between the $from/$till range. In this example, the function should return true because $checkFrom is between the $from/$till range. But also the following should be true:

$checkFrom = 22:00
$checkTill = 23:45

标签: php time
4条回答
劫难
2楼-- · 2019-01-15 05:01

Following function works even for older versions of php:

function isBetween($from, $till, $input) {
    $fromTime = strtotime($from);
    $toTime = strtotime($till);
    $inputTime = strtotime($input);

    return($inputTime >= $fromTime and $inputTime <= $toTime);
}
查看更多
贪生不怕死
3楼-- · 2019-01-15 05:03

based on 2astalavista's answer:

You need to format the time correctly, one way of doing that is using PHP's strtotime() function, this will create a unix timestamp you can use to compare.

function checkUnixTime($to, $from, $input) {
    if (strtotime($input) > strtotime($from) && strtotime($input) < strtotime($to)) {
        return true;
    }
}
查看更多
Summer. ? 凉城
4楼-- · 2019-01-15 05:05

Try this:

function checkTime($From, $Till, $input) {
    if ($input > $From && $input < $Till) {
        return True;
    } else {
        return false;
}
查看更多
Evening l夕情丶
5楼-- · 2019-01-15 05:10

Try this function:

function isBetween($from, $till, $input) {
    $f = DateTime::createFromFormat('!H:i', $from);
    $t = DateTime::createFromFormat('!H:i', $till);
    $i = DateTime::createFromFormat('!H:i', $input);
    if ($f > $t) $t->modify('+1 day');
    return ($f <= $i && $i <= $t) || ($f <= $i->modify('+1 day') && $i <= $t);
}

demo

查看更多
登录 后发表回答