You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:基于营业时间,用PHP时间函数判断营业状态的功能异常修复

Fixing Your PHP Business Hours Status Function

Hey there, let's work through why your function is incorrectly showing "closed" when the business should be marked as open. The core problem here is how you're handling overnight business hours (like your example of 9:00 AM to 3:30 AM the next day) — your current code only checks if the time falls within a same-day window, which doesn't work for cross-midnight shifts.

What's Going Wrong

When your closing time (03:30AM) is earlier than your opening time (09:00AM), that signals the business operates past midnight. But your original logic only verifies if the current time is strictly between open and close on the same day — which is impossible for overnight schedules, so it always returns "closed".

Fixed Function Code

Here's an updated version that handles both same-day and overnight hours correctly:

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

    // Detect overnight business hours
    if ($closeTime < $openTime) {
        // Overnight rule: current time is either after opening OR before closing
        if ($nowTime >= $openTime || $nowTime <= $closeTime) {
            $status = 'open';
        }
    } else {
        // Same-day rule: current time falls between open and close
        if ($nowTime > $openTime && $nowTime < $closeTime) {
            $status = 'open';
        }
    }

    return $status;
}

// Test overnight case
echo OperationHours('09:00AM', '03:30AM');
// Test same-day case
echo OperationHours('09:00AM', '06:00PM');

Key Improvements

  • Added a check for when $closeTime is earlier than $openTime to identify overnight shifts
  • For overnight schedules, we check if the current time is after opening (and before midnight) OR before closing (after midnight)
  • Retained the original logic for same-day hours to keep compatibility with regular business schedules

Quick Tip

If you need accurate local time checks (critical for businesses in specific regions), add a timezone when creating your DateTime objects:

$timezone = new DateTimeZone('Europe/London'); // Replace with your target timezone
$nowTime = DateTime::createFromFormat('h:iA', $current_time, $timezone);
$openTime = DateTime::createFromFormat('h:iA', $open, $timezone);
$closeTime = DateTime::createFromFormat('h:iA', $close, $timezone);

内容的提问来源于stack exchange,提问作者Peter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:15:33