如何使用PHP显示2个日期的所有月份?

时间:2017-01-17 03:25:05

标签: php

我有一个名为$conn_date的变量,其值为2016-09-18

现在我想显示从2016-09-18直到的所有月份。但是使用下面的PHP代码,我无法获得当前月份。

$begin = new DateTime($conn_date); // value is : 2016-09-18
$end = new DateTime( date("Y-m-d") );

$interval = DateInterval::createFromDateString('1 Month');
$period = new DatePeriod($begin, $interval, $end);

$ok = array();
foreach ( $period as $k=>$dt ) {  
    if ( $dt->format("Y-m-d") ) {        
        $ok[] = $dt->format("Y-m-d");
    }
}

echo '<pre>';
    print_r($ok);
echo '</pre>';

输出

Array
(
    [0] => 2016-09-18
    [1] => 2016-10-18
    [2] => 2016-11-18
    [3] => 2016-12-18
)

我想展示当前的月份,我该怎么做?

3 个答案:

答案 0 :(得分:2)

$begin = new DateTime($conn_date); // value is : 2016-09-18
$end = new DateTime( date("Y-m-d") );
$end->add(new DateInterval("P1M"));
$interval = DateInterval::createFromDateString('1 Month');
$period = new DatePeriod($begin, $interval, $end);

$ok = array();
foreach ( $period as $k=>$dt ) {  
    if ( $dt->format("Y-m-d") ) {        
        $ok[] = $dt->format("Y-m-d");
    }
}

echo '<pre>';
    print_r($ok);
echo '</pre>';

//这里&#34; P1M&#34;为期一个月,访问http://php.net/manual/en/datetime.add.php

答案 1 :(得分:0)

$a = "2007-01-01";
$b = "2008-02-15";

$i = date("Ym", strtotime($a));
while($i <= date("Ym", strtotime($b))){
    echo $i."\n";
    if(substr($i, 4, 2) == "12")
        $i = (date("Y", strtotime($i."01")) + 1)."01";
    else
        $i++;
}

答案 2 :(得分:0)

您只需要在结束日期添加一个间隔。在您的情况下$end->modify('1 month')

所以完整的代码:

$begin = new DateTime('2016-09-18');
$end = new DateTime();

$unitQty = '1 month';
$interval = DateInterval::createFromDateString($unitQty);
$period = new DatePeriod($begin, $interval, $end->modify($unitQty));

$ok = array();
foreach ( $period as $k=>$dt ) {
    if ( $dt->format("Y-m-d") ) {
        $ok[] = $dt->format("Y-m-d");
    }
}