我有$date1 = '2014-09-01'
和$date2 = '2015-02-01'
。我可以从$date1
到$date2
这样的几个月和几年:
答案 0 :(得分:3)
实例化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
答案 1 :(得分:1)
$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
答案 2 :(得分:0)
使用DateTime和DateInterval类使用add()等几种方法来增加计数器,并使用简单的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
}