如何列出两个日期之间的所有月份 [英] How to list all months between two dates

查看:103
本文介绍了如何列出两个日期之间的所有月份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在列出两个日期之间的所有月份。

I'm trying to list all months between two dates.

开始日期是: 2010-12-02 最后一个日期是: 2012-05-06

For example; start date is: 2010-12-02 and last date is: 2012-05-06

我想列出如下:

2010-12
2011-01
2011-02
2011-03
2011-04
.
.
.
2012-04
2012-05

这是我尝试过的它根本不起作用:

This is what I have tried and it is not working at all:

    $year_min = 2010;
    $year_max = 2012;
    $month_min = 12;
    $month_max = 5;
    for($y=$year_min; $y<=$year_max; $y++)
    {
        for($m=$month_min; $m<=$month_max; $m++)
        {
            $period[] = $y.$m;
        }
    }


推荐答案

strong> PHP 5.3

PHP 5.3

$start    = new DateTime('2010-12-02');
$start->modify('first day of this month');
$end      = new DateTime('2012-05-06');
$end->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period   = new DatePeriod($start, $interval, $end);

foreach ($period as $dt) {
    echo $dt->format("Y-m") . "<br>\n";
}

请参阅

PHP 5.4或更高版本

PHP 5.4 or newer

$start    = (new DateTime('2010-12-02'))->modify('first day of this month');
$end      = (new DateTime('2012-05-06'))->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period   = new DatePeriod($start, $interval, $end);

foreach ($period as $dt) {
    echo $dt->format("Y-m") . "<br>\n";
}

我们将开始和结束日期修改为本月初的部分很重要如果我们没有,而今天在二月份的最后一天(即非闰年的28天,闰年的29个),那么这将跳过二月。

The part where we modify the start and end dates to the first of the month is important. If we didn't, and the current day higher then the last day in February (i.e. 28 in non-leap years, 29 in leap years) this would skip February.

这篇关于如何列出两个日期之间的所有月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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