【问题标题】:PHP Check if time is between two times regardless of datePHP检查时间是否在两次之间,无论日期如何
【发布时间】:2015-01-23 17:46:36
【问题描述】:

我正在编写一个脚本,无论日期如何,我都必须检查时间范围是否在两次之间。

例如,我有这两个日期:

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

我有以下时间检查:

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

我需要创建一个脚本,如果其中一个检查值在 $from/$till 范围之间,它将返回 true。在此示例中,该函数应返回 true,因为 $checkFrom 介于 $from/$till 范围之间。但以下内容也应该是正确的:

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

【问题讨论】:

  • 只是比较它们...if ($from <= $checkFrom && $checkFrom <= $till)
  • 针对这种情况实施脚本需要一些猜测。因为不知道需要检查的时间是今天(对于您的 from 变量)还是明天(对于您的 till 变量)。
  • 05:50 这样的时间不是有效变量,因此您必须将它们用作以下之一:array(5,50)"05:50" 或时间戳(整数)

标签: php time


【解决方案1】:

试试这个:

function checkTime($From, $Till, $input) {
    if ($input > $From && $input < $Till) {
        return True;
    } else {
        return false;
}

【讨论】:

  • 这不起作用,如果我将 05:50 作为 $input 传递,该函数将返回 false,尽管它介于 $from 和 $till 之间。
【解决方案2】:

基于 2astalavista 的回答:

您需要正确格式化时间,其中一种方法是使用 PHP 的 strtotime() 函数,这将创建一个可用于比较的 unix 时间戳。

function checkUnixTime($to, $from, $input) {
    if (strtotime($input) > strtotime($from) && strtotime($input) < strtotime($to)) {
        return true;
    }
}

【讨论】:

    【解决方案3】:

    试试这个功能:

    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

    【讨论】:

    • 对于那些不知道感叹号含义的人:!将所有字段(年、月、日、小时、分钟、秒、分数和时区信息)重置为 Unix Epoch 没有!,所有字段将设置为当前日期和时间。参考:php.net/manual/en/datetime.createfromformat.php
    【解决方案4】:

    以下功能甚至适用于旧版本的 php:

    function isBetween($from, $till, $input) {
        $fromTime = strtotime($from);
        $toTime = strtotime($till);
        $inputTime = strtotime($input);
    
        return($inputTime >= $fromTime and $inputTime <= $toTime);
    }
    

    【讨论】:

      【解决方案5】:

      此代码适用于我

      if($start_time=date("H:i")) {

      }

      【讨论】:

        【解决方案6】:
        $tomorrow = new DateTime('tomorrow');
        
        $currentTime = strtotime(date('Y-m-d H:i'));
        $startTime = strtotime(date('Y-m-d').' 23:00');
        
        // $endtime date will be next day during time 23 to 00.
        if (strtotime(date('H:i')) > strtotime('23:00') && strtotime(date('H:i')) < strtotime('00:00')) {
            $endTime = strtotime($tomorrow->format('Y-m-d').' 07:00');
        } else {
            $endTime = strtotime(date('Y-m-d').' 07:00');
        }
        
        $flag = false;
        if ($currentTime > $startTime || $currentTime < $endTime) {
            $flag = true;
        }
        
        return $flag;
        

        【讨论】:

          猜你喜欢
          • 2013-07-15
          • 2017-11-29
          • 2012-09-19
          • 1970-01-01
          • 1970-01-01
          • 2013-04-01
          • 1970-01-01
          相关资源
          最近更新 更多