Gor*_*don 77
尝试
$start = $month = strtotime('2009-02-01');
$end = strtotime('2011-01-01');
while($month < $end)
{
echo date('F Y', $month), PHP_EOL;
$month = strtotime("+1 month", $month);
}
Run Code Online (Sandbox Code Playgroud)
请注意http://php.net/manual/de/datetime.formats.relative.php
相对月份值是根据它们经过的月份长度计算的.一个例子是"+ 2个月2011-11-30",这将产生"2012-01-30".这是因为11月份为30天,12月为31天,共计61天.
从PHP5.3开始,您可以使用http://www.php.net/manual/en/class.dateperiod.php
Gla*_*vić 34
DateTime,DateInterval和DatePeriod类组合的示例:
$start = new DateTime('2009-02-01');
$interval = new DateInterval('P1M');
$end = new DateTime('2011-01-01');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
echo $dt->format('F Y') . PHP_EOL;
}
Run Code Online (Sandbox Code Playgroud)
3s2*_*2ng 20
接受的答案不是正确的方法.
我试过这个片段但它无法正常工作.如果您的开始日期是月末,而结束日期是第3个月的开始日期.
例如:2014-08-31 - 2014-10-01
预计应该是.
更好的解决方案是:
$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";
}
Run Code Online (Sandbox Code Playgroud)
$start = strtotime('2011-09-01');
$end = strtotime('2013-12-01');
while($start < $end)
{
echo date('F Y', $start) . '<br>';
$start = strtotime("+1 month", $start);
}
Run Code Online (Sandbox Code Playgroud)