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

PHP实现:根据总周数及时间条件获取连续周四日期

修正PHP代码以按规则获取连续周四日期

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

  • 循环内重复调用strtotime("next Thursday")会始终返回同一个日期,因为每次都是基于当前时间计算,没有累加周偏移
  • 未处理当前时间是否超过周四20:00的阈值逻辑,无法区分两种预期输出场景

修正方案(推荐使用DateTime类,可读性更强)

$totalWeek = 4;
$today = new DateTime();

// 生成本周四20:00的时间阈值
$threshold = (clone $today)->modify('this Thursday')->setTime(20, 0, 0);

// 确定起始周四:当前时间晚于等于阈值则从下周四开始,否则从本周四开始
$currentThursday = $today >= $threshold 
    ? (clone $today)->modify('next Thursday') 
    : (clone $today)->modify('this Thursday');

// 循环获取连续的周四日期
for ($i = 0; $i < $totalWeek; $i++) {
    // 输出大写格式的日期
    echo strtoupper($currentThursday->format('d-M-Y')) . PHP_EOL;
    // 日期累加一周
    $currentThursday->modify('+1 week');
}

逻辑说明

  1. 阈值判断:通过克隆当前时间对象,生成本周四20:00的时间节点,对比当前时间决定起始周四
  2. 连续日期生成:每次循环输出当前周四后,将日期累加一周,确保得到连续的周四序列
  3. 格式处理:用strtoupper()将日期格式转为大写,匹配预期输出样式

场景验证

  • 场景1:当前时间早于周四20:00(例:2023-09-19 18:00)
    输出结果:
    21-SEP-2023
    28-SEP-2023
    05-OCT-2023
    12-OCT-2023
    
  • 场景2:当前时间为周四20:01及以后(例:2023-09-21 20:01)
    输出结果:
    28-SEP-2023
    05-OCT-2023
    12-OCT-2023
    19-OCT-2023
    

替代方案(使用strtotime时间戳)

如果偏好使用时间戳处理,可参考以下代码:

$totalWeek = 4;
$now = time();
$threshold = strtotime('this Thursday 20:00:00');

// 确定起始周四的时间戳
$startThursday = $now >= $threshold 
    ? strtotime('next Thursday') 
    : strtotime('this Thursday');

// 循环输出连续日期
for ($i = 0; $i < $totalWeek; $i++) {
    echo strtoupper(date('d-M-Y', $startThursday + $i * 7 * 24 * 3600)) . PHP_EOL;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 14:18:18