2010-01-28 143 views

回答

70

尝试

$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); 
} 

心灵的音符http://php.net/manual/de/datetime.formats.relative.php

相对月份值是基于他们经过几个月的长度来计算。一个例子是“2011年2月30日+2月”,这将产生“2012-01-30”。这是由于11月份为30天,而12月份为31天,共计61天。

作为PHP5.3的可以使用http://www.php.net/manual/en/class.dateperiod.php

+0

我试过这个片段,它不能正常工作。如果您的开始日期是月底,结束日期是第3个月的开始日期。例如:2014-08-31 - 2014-10-01 – 3s2ng 2014-10-01 09:24:53

+2

@ 3s2ng是的,但这是相对时间格式的预期行为。查看我的答案更新。 – Gordon 2014-10-01 09:50:57

+0

这将做到这一点。谢谢。 – 3s2ng 2014-10-01 10:33:01

26

实施例的DateTimeDateIntervalDatePeriod类组合:

$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; 
} 
2
$start = strtotime('2011-09-01'); 
$end = strtotime('2013-12-01'); 
while($start < $end) 
{ 
    echo date('F Y', $start) . '<br>'; 
    $start = strtotime("+1 month", $start); 
} 
1

我有是在结果中最佳的方法:

$begin = new DateTime('2014-07-14'); 
$end = new DateTime('2014-08-01'); 
$end = $end->modify('+1 month'); 
$interval = DateInterval::createFromDateString('1 month'); 

$period = new DatePeriod($begin, $interval, $end); 

foreach($period as $dt) { 
    var_dump($dt->format("m")); 
} 

A @Glavic的方法

15

接受的答案不是正确的方法。

我试过这段代码,它不能正常工作。如果您的开始日期是月底,结束日期是第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"; 
} 

参考:How to list all months between two dates

1

我喜欢接受的答案的简单性,但作为3s2ng,它并不总是工作。所以我这样tweeked它:

$start = strtotime('2009-02-01'); 
    $startmoyr = date('Y', $start) . date('m', $start); 
    $end = strtotime('2013-12-01'); 
    $endmoyr = date('Y', $end) . date('m', $end); 

    while ($startmoyr <= $endmoyr) { 
     echo date("F Y", $start) . "<br>"; 
     $start = strtotime("+1month", $start); 
     $startmoyr = date('Y', $start) . date('m', $start); 
    } 
相关问题