如何显示 PHP 中两个日期的月份和年份

how to show months and years from two date in PHP

我有 $date1 = '2014-09-01'$date2 = '2015-02-01'。我可以像这样得到从 $date1$date2 的月份和年份吗:

实例化 DateTime 对象并循环遍历它们:

$date1 = new \DateTime('2014-09-01');
$date2 = new \DateTime('2015-02-01');

while ($date1 <= $date2) {
    echo $date1->format('Y-M') . '<br>';
    $date1->add(new \DateInterval('P1M')); // increase by one month
}

结果:

2014-Sep
2014-Oct
2014-Nov
2014-Dec
2015-Jan
2015-Feb
$date1 = new DateTime("2014-09-01");
$date2 = new DateTime("2015-02-01");

while ($date1 <= $date2) {

    echo $date1->format("Y-M")."\n";
    $date1->modify("+1 month");
}

结果:

2014-Sep
2014-Oct
2014-Nov
2014-Dec
2015-Jan
2015-Feb

使用 DateTime and DateInterval class 和 add() 等方法来增加计数器和 format() 以使用简单的 while 循环进行日期格式化

$startDate= new DateTime("2014-09-01");
$endDate = new DateTime("2015-02-01");
$oneMonth=new DateInterval('P1M');      //for 1 month interval

while ($startDate <= $endDate) {
  print $startDate->format("Y-M")."\n";  //date formating as your requirement
  $startDate->add($oneMonth);          //increment counter by 1 month
 }