循环遍历日期范围内的所有月份? [英] Loop through all months in a date range?

查看:69
本文介绍了循环遍历日期范围内的所有月份?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个开始日期(比如 2009-02-01)和一个结束日期(比如 2010-01-01),我如何创建一个循环遍历范围内的所有日期(月份)?

If I have a start date (say 2009-02-01) and an end date (say 2010-01-01), how can I create a loop to go through all the dates (months) in the range?

推荐答案

尝试

$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

相对月份值是根据它们经过的月份长度计算的.一个例子是+2 月 2011-11-30",它会产生2012-01-30".这是由于 11 月的长度为 30 天,而 12 月的长度为 31 天,总共产生 61 天.

Relative month values are calculated based on the length of months that they pass through. An example would be "+2 month 2011-11-30", which would produce "2012-01-30". This is due to November being 30 days in length, and December being 31 days in length, producing a total of 61 days.

从 PHP5.3 开始,您可以使用 http://www.php.net/manual/en/class.dateperiod.php

As of PHP5.3 you can use http://www.php.net/manual/en/class.dateperiod.php

这篇关于循环遍历日期范围内的所有月份?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆