这个问题在这里已有答案:
如何列出两个日期之间的所有月份 4个答案这个问题在几个月似乎与旧问题类似,但我有一个特殊问题。 我不是要计算两个日期之间的月份,但我想把两个日期包括在内。 我解释。 我有2个约会:
$begin = new DateTime( '2014-07-20' ); $end = new DateTime( '2014-10-10' );在这两个日期之间,我有4个月的时间:7月,8月,9月,10月。 但是使用我正在使用的脚本,我无法找到4个月但仅包含3.这是脚本:
$interval = DateInterval::createFromDateString('1 month'); $period = new DatePeriod($begin, $interval, $end); $counter = 1; foreach($period as $dt) { echo $dt->format( 'm' ); $counter++; } echo $counter;如何计算循环中的所有这4个月?
This question already has an answer here:
How to list all months between two dates 4 answersThis questions will seems similar to old ones about month but I have a special issue. I am not trying to count the months between two dates, but I am trying to get the months included in two dates. I explain. I have 2 dates :
$begin = new DateTime( '2014-07-20' ); $end = new DateTime( '2014-10-10' );Between those two dates, I have 4 months included : July, August, September, October. But with the script I am using, I am not able to find 4 months included but only 3. This is the script :
$interval = DateInterval::createFromDateString('1 month'); $period = new DatePeriod($begin, $interval, $end); $counter = 1; foreach($period as $dt) { echo $dt->format( 'm' ); $counter++; } echo $counter;How to count all those 4 months in a loop ?
最满意答案
您可以使用简单的while()循环执行此操作:
$begin = new DateTime('2014-07-20'); $end = new DateTime('2014-10-10'); while ($begin <= $end) { echo $begin->format('Y-m'), "\n"; $begin->modify('first day of next month'); }演示
You can do this with simple while() loop:
$begin = new DateTime('2014-07-20'); $end = new DateTime('2014-10-10'); while ($begin <= $end) { echo $begin->format('Y-m'), "\n"; $begin->modify('first day of next month'); }demo
更多推荐
发布评论