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

PHP每周特定时段执行函数问题:周日起48小时内触发逻辑修复

修复方案

原代码存在两个核心问题:

  • 起始时间计算错误:strtotime($checkday)在非周日运行时,会指向下一个周日而非当前周的周日,导致判断逻辑完全偏离需求
  • 结束时间计算错误:错误以当天0点为起点加48小时,而非以当前周的周日0点为基准

以下是修复后的可直接运行代码:

$checkday = "Sunday";
$period = 48; // 改为整数类型更规范

// 获取当前周的周日00:00:00时间戳
// 今天是周日则取当天0点,否则取上一个周日0点
$todayWeekday = date('w'); // 0=周日,1=周一...6=周六
$startTimestamp = $todayWeekday == 0 
    ? strtotime('today 00:00:00') 
    : strtotime('last Sunday 00:00:00');

// 计算结束时间:周日0点 + 48小时(即周二00:00:00)
$endTimestamp = $startTimestamp + $period * 3600;

// 判断当前时间是否在目标时段内
if (time() >= $startTimestamp && time() <= $endTimestamp) {
    // 执行你的指定函数
    // your_target_function();
}

代码说明

  1. 精准定位当前周周日:通过date('w')判断当前周几,确保起始时间始终是当前周期的周日0点,不会跳转到下一周
  2. 时间戳直接运算:避免多次调用strtotime解析字符串,性能更高效,逻辑也更清晰
  3. 类型规范:将$period改为整数,避免字符串拼接带来的潜在问题

简化写法(兼容多数环境)

如果服务器时区的周起始规则为周日,也可以用更简洁的方式获取起始时间:

$startTimestamp = strtotime('this Sunday 00:00:00');
$endTimestamp = $startTimestamp + 48 * 3600;

if (time() >= $startTimestamp && time() <= $endTimestamp) {
    // 执行函数
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 04:10:32