Reputation: 91
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 e.g. 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"));
Upvotes: 1
Views: 1773
Reputation: 1477
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;
}
Upvotes: 0
Reputation: 43562
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');
}
Upvotes: 3
Reputation: 11984
$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);
Upvotes: 0
Reputation: 9635
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"));
}
Upvotes: 0