获取PHP中两个日期之间的所有月份[重复](Get all months included between two dates in PHP [duplicate])

编程入门 行业动态 更新时间:2024-10-23 13:33:46
获取PHP中两个日期之间的所有月份[重复](Get all months included between two dates in PHP [duplicate])

这个问题在这里已有答案:

如何列出两个日期之间的所有月份 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 answers

This 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

更多推荐

本文发布于:2023-08-01 04:07:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1352883.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两个   日期   PHP   months   duplicate

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!