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

PHP中如何通过for/foreach循环遍历DateTime日期并为每个日期加3天

问题原因

你原代码的问题有两个:

  1. 不需要嵌套两层循环,遍历每一天的同时直接给当前日期加3天即可,不需要额外遍历内层$j
  2. PHP中DateTime对象是引用传递,直接$i = $begin赋值不会创建新对象,修改$i会同步修改原$begin对象,导致日期计算错乱

正确实现(for循环版本)

<?php
$begin = new DateTime("2022-01-01");
// 结束日期克隆独立对象,避免被后续修改影响
$end = (clone $begin)->setDate(2022, 1, 31);

// 每次循环克隆当前日期对象,避免引用传值问题
for ($current = clone $begin; $current <= $end; $current->modify('+1 day')) {
    // 加3天的时候也要克隆,避免修改当前遍历的日期节点
    $add3Day = (clone $current)->modify('+3 day');
    echo $current->format("M d, Y") . ' => ' . $add3Day->format("M d, Y") . '<br/><br/>';
}
?>

运行后即可输出你需要的效果:从Jan 01, 2022 => Jan 04, 2022一直到Jan 31, 2022 => Feb 03, 2022。


可选:foreach版本(用DatePeriod更简洁)

<?php
$begin = new DateTime("2022-01-01");
// DatePeriod是左闭右开规则,所以结束日期要设为区间最后一天的下一天
$end = new DateTime("2022-02-01");
$interval = new DateInterval('P1D');
$dateRange = new DatePeriod($begin, $interval, $end);

foreach ($dateRange as $current) {
    $add3Day = (clone $current)->modify('+3 day');
    echo $current->format("M d, Y") . ' => ' . $add3Day->format("M d, Y") . '<br/><br/>';
}
?>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 18:45:01