【发布时间】:2019-05-29 00:32:45
【问题描述】:
我想使用 PHP DateInterval 来迭代几个月:
$from = new DateTime();
$from->setDate(2014, 1, 31);
$period = new DatePeriod($from, new DateInterval('P1M'), 12);
我希望它返回 1 月 31 日、2 月 28 日(因为 DateInterval 是 1 个月),但它实际上返回 1 月 31 日、3 月 3 日、4 月 3 日......因此跳过了 2 月。
有没有办法简单地做到这一点?
谢谢!
编辑:作为参考,这是一个似乎涵盖大多数用例的解决方案:
$date = new DateTime('2014-01-31');
$start = $date->format('n');
for ($i = 0; $i < 28; $i++) {
$current = clone $date;
$current->modify('+'.$i.' month');
if ($current->format('n') > ($start % 12) && $start !== 12) {
$current->modify('last day of last month');
}
$start++;
echo $current->format('Y-m-d').PHP_EOL;
}
【问题讨论】: