gpt4 book ai didi

php - 如何列出两个日期之间的所有月份

转载 作者:IT王子 更新时间:2023-10-29 00:40:03 25 4
gpt4 key购买 nike

我正在尝试列出两个日期之间的所有月份。

例如;开始日期是:2010-12-02,最后日期是:2012-05-06

我想列出如下内容:

2010-12
2011-01
2011-02
2011-03
2011-04
.
.
.
2012-04
2012-05

这是我尝试过的,但根本不起作用:

    $year_min = 2010;
$year_max = 2012;
$month_min = 12;
$month_max = 5;
for($y=$year_min; $y<=$year_max; $y++)
{
for($m=$month_min; $m<=$month_max; $m++)
{
$period[] = $y.$m;
}
}

最佳答案

PHP 5.3

$start    = new DateTime('2010-12-02');
$start->modify('first day of this month');
$end = new DateTime('2012-05-06');
$end->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($start, $interval, $end);

foreach ($period as $dt) {
echo $dt->format("Y-m") . "<br>\n";
}

See it in action

PHP 5.4 或更新版本

$start    = (new DateTime('2010-12-02'))->modify('first day of this month');
$end = (new DateTime('2012-05-06'))->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($start, $interval, $end);

foreach ($period as $dt) {
echo $dt->format("Y-m") . "<br>\n";
}

我们将开始日期和结束日期修改为月初的部分很重要。如果我们不这样做,并且当前日期高于 2 月的最后一天(即非闰年的 28 天,闰年的 29 天),这将跳过 2 月。

关于php - 如何列出两个日期之间的所有月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18742998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com