简体   繁体   中英

GET 12 months in future and 12 months in past

How can i loop through the past 12 months and also the future 12 months.

The easiest way i imainge is just looping through the past 24 months by starting a year ahead eg Jan 2015

My current code returns the past 12 months

for ($i = 1; $i <= 12; $i++) {
$my = date("F Y", strtotime( date( 'Y-m-01' )." -$i months"));
$ymd = date("Y-m-d", strtotime( date( 'Y-m-01' )." -$i months"));

This can simply be accomplished via DateTime extension:

$months = 12; # number of months before and after current month
$dt = new DateTime('first day of this month'); # select first day in current month
$dt->modify("-$months month");
for ($i = 0; $i <= $months * 2; $i++) {
    echo $dt->format('M Y'), "\n";
    $dt->modify('+1 month');
}

demo

try this

for ($i = 1; $i <= 12; $i++) 
{
$my = date("F Y", strtotime( date( 'Y-m-01' )." -$i months"));
$ymd = date("Y-m-d", strtotime( date( 'Y-m-01' )." -$i months"));

$f_my = date("F Y", strtotime( date( 'Y-m-01' )." +$i months"));
$f_ymd = date("Y-m-d", strtotime( date( 'Y-m-01' )." +$i months"));

}
$arrPast = array();
$arrFut  = array();
for ($i = 1; $i <= 12; $i++) {
    $arrPast[]  = date("Y-m-d", strtotime( date( 'Y-m-d' )." -$i months"));
    $arrFut[]   = date("Y-m-d", strtotime( date( 'Y-m-01' )." +$i months"));
}

echo 'Past 12 months <pre>';
print_r($arrPast);

echo 'Future 12 months <pre>';
print_r($arrFut);

It should be like

$pastDate = date("Y-m-d", strtotime( date( 'Y-m-01' )." -12 months"));

$futureDate = date("Y-m-d", strtotime( date( 'Y-m-01' )." +12 months"));

for ($i = $pastDate; $i <= $futureDate; $i = date("Y-m-d", strtotime($i." +1 months")))
{
    echo "<br />Current Month(Y-m-d) is ".$i;
}

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