简体   繁体   中英

How to show all month from 2 dates using PHP?

I have a variable called $conn_date which value is 2016-09-18 .

Now I want to show all months from 2016-09-18 to till now. But using bellow php code I can't get current month.

$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>';

Output :

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

I want to show current months too, How can I do this ?

$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>';

//Here "P1M" is a one-month duration, Visit http://php.net/manual/en/datetime.add.php

$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++;
}

You just need to add one interval to your end date. In your case $end->modify('1 month')

So the full code:

$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");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM