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

每日执行向设备推送订单的脚本,判断日期的if条件写法是否正确?

日期对比逻辑合理性说明

原有写法的缺陷

你当前使用的$delivery_date->diff($today)->days === 0写法,仅在两个日期的时间区间不跨自然日的场景下可用,存在两个明显的逻辑漏洞:

  • new DateTime()生成的$today默认携带当前时分秒,若$checkout->day存储的是不带时间的纯日期,生成的$delivery_date默认时间为0点,脚本在午夜临界时间执行时容易出现日期判断偏差
  • diff()方法的days属性统计的是两个日期间隔的完整24小时天数,若两个时间相差不足24小时但跨了自然日(比如5月20日23:30和5月21日00:30),days也会返回0,完全不符合你判断自然日相等的需求

推荐的正确写法

直接将两个日期统一格式化为年月日字符串对比,逻辑清晰且无临界值问题:

// 实例化今日日期时直接重置时间为0点,完全排除时分秒干扰
$today = new DateTime('today');

foreach($orders as $order){
    $checkout = new Checkout();
    $checkout->get($order['id']);
    $delivery_date = new DateTime($checkout->day);
    $restaurant = $checkout->getRestaurant();
    // 直接对比格式化后的自然日字符串,100%匹配需求
    if($delivery_date->format('Y-m-d') === $today->format('Y-m-d')) {
        $popina_response = ''; // 提前初始化变量,避免未定义警告
        if (!empty($restaurant->token)) {
            if ($popina_response = Foxorders_Popina::sendNewOrder($checkout)) {
                $checkout->popina_notified = 1;
                $checkout->popina_response = $popina_response;
            }
            // 用in_array优化多条件判断,可读性更高
            $allowed_responses = [
                '{"ok":true}',
                'Shop not found',
                '{"error":"Shop not found"}'
            ];
            if (in_array($popina_response, $allowed_responses)) {
                $checkout->popina_retry = 0;
            }
            $checkout->save();
        }
    }
}

其他小优化点

  • 原有判断isset($restaurant->token) && !empty($restaurant->token)可以简化为!empty($restaurant->token),empty()本身会先判断变量是否存在,再判断值是否为空
  • 提前初始化$popina_response变量,避免sendNewOrder返回false时,下方判断用到未定义变量抛出警告

内容的提问来源于stack exchange,提问作者치노장인

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 06:06:03