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'); }
逻辑说明
- 阈值判断:通过克隆当前时间对象,生成本周四20:00的时间节点,对比当前时间决定起始周四
- 连续日期生成:每次循环输出当前周四后,将日期累加一周,确保得到连续的周四序列
- 格式处理:用
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
相关产品推荐
相关产品推荐

