1
votes

I want a loop that checks the current month, 12 months in the future and 4 months in the past.

For example: Today is 1st August 08. My loop should go through April, May, June, July, August, September, October, November, December, January, February, March, April, May, June, July, and August.

I have tried strotime but I don't know how I can loop 4 months back and 12 months in the future.

Here is my code

$i = 1; 
$month = strtotime('2013-08-01');

    while($i <= 12) {
        $month_name = date('F', $month);
        echo $month_name;
        echo "<br>";

        $month = strtotime('+1 month', $month);
        $i++;
6
start with the timestamp four months ago, and expand your loop to 16 months would be an easy way to goMichael Kunst

6 Answers

3
votes

I think Yoshi was almost there with his answer, but using DatePeriod with DateTime is more consistent and makes for more readable code IMHO:-

$oneMonth = new \DateInterval('P1M');
$startDate = \DateTime::createFromFormat('d H:i:s', '1 00:00:00')->sub(new \DateInterval('P4M'));
$period = new \DatePeriod($startDate, $oneMonth, 16);

foreach($period as $date){
    //$date is an instance of \DateTime. I'm just var_dumping it for illustration
    var_dump($date);
}

See it working

2
votes

This can be quite tricky, here's how I would do it:

$month = date("n", "2013-08-01") - 1; // -1 to get 0-11 so we can do modulo

// since you want to go back 4 you can't just do $month - 4, use module trick:
$start_month = $month + 8 % 12;
// +8 % 12 is the same is -4 but without negative value issues
// 2 gives you: 2+8%12 = 10 and not -2

for ($i = 0; $i < 16; $i += 1) {
    $cur_month = ($start_month + $i) % 12 + 1; // +1 to get 1-12 range back
    $month_name = date('F Y', strtotime($cur_month . " months"));
    var_dump(month_name);
}
1
votes

something like this?:

$start = -4;
$end = 12;

for($i=$start; $i<=$end;$i++) {
    $month_name = date('F Y', strtotime("$i months"));
    echo $month_name;
    echo "<br>";
}
1
votes

Your code, just slightly modified.

date_default_timezone_set('UTC');

$i = 1;
$month = strtotime('-4 month');

while($i <= 16) {
    $month_name = date('F', $month);
    echo $month_name;
    echo "<br>";

    $month = strtotime('+1 month', $month);
    $i++;
}
1
votes

Simplest solution:

for($i=-4; $i<=12; $i++) {
    echo date("F",strtotime( ($i > 0) ? "+$i months" : "$i months") )."\n";
}

Explanation:

The loop starts at -4 and goes all the way upto 12 (total 17, including 0). The ternary statement inside strtotime() simply checks if $i is positive, and if it is, a + is inserted so that we'll get the results for strtotime("+1 months") and similar.

Ta-da!

0
votes

Using DateTime is the easiest and more readable way. I would do it like this:

$from = new DateTime('-4 month');
$to   = new DateTime('+12 month');
while($from < $to){
  echo $from->modify('+1 month')->format('F');
}