代码之家  ›  专栏  ›  技术社区  ›  Peter

使用php time函数根据打开和关闭时间检查业务状态

  •  1
  • Peter  · 技术社区  · 8 年前

    我试图根据他们提供的打开和关闭时间来显示业务运营状态,但即使我在网上有几个例子,它似乎也不起作用。 请告诉我,问题可能是以不同的方式提出的,是否有人可以帮助我解决这个问题,因为下面的函数显示关闭,即使业务打开。

    我的PHP函数

    function OperationHours($open, $close){
        $status = 'closed';
        $current_time = date('h:iA');
        $nowTime = DateTime::createFromFormat('h:iA', $current_time);
        $openTime = DateTime::createFromFormat('h:iA', $open);
        $closeTime = DateTime::createFromFormat('h:iA', $close);
            if ($nowTime > $openTime && $nowTime < $closeTime){
                $status = 'open';
            }
        return $status;
    }
    
    /*function OperationHours($open, $close){
        $status = 'closed';
        $timestamp = time();
        $currentTime = (new DateTime())->setTimestamp($timestamp);
        $openTime = DateTime::createFromFormat('h:iA', $open);
        $closeTime = DateTime::createFromFormat('h:iA', $close);
            if(($openTime < $currentTime) && ($currentTime < $closeTime)) {
                $status = 'open';
            }
        return $status;
    }*/
    
    echo OperationHours('09:00AM', '03:30AM');
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Taha Paksu    8 年前

    您需要添加一个检查关闭时间是否属于前一天:

    function OperationHours($open, $close){
        $status = 'closed';
        $nowTime = new DateTime("NOW", new DateTimeZone("GMT"));    
        $openTime = DateTime::createFromFormat('h:iA', $open, new DateTimeZone("GMT"));
        $closeTime = DateTime::createFromFormat('h:iA', $close, new DateTimeZone("GMT"));
    
        // check if the close time is before the opening time       
        if($closeTime <= $openTime){
            $closeTime->add(new DateInterval("P1D"));
        }
    
        if ($nowTime > $openTime && $nowTime < $closeTime){
            $status = 'open';
        }
        return $status;
    }
    
    echo OperationHours('09:00AM', '11:30AM');
    

    如果使用时区检查日期,请设置 GMT 到定义的时区。否则它会有一个时区差 10:00AM +0300 作为 07:00AM +0000 (GMT) 然后它会回来的 closed .