Carl0s1z
Carl0s1z

Reputation: 4723

PHP: Can't get month at the right year

For the code below i want to have the current month and the next 12 months with the year. Im using a loop for it, everyting works fine except for "January". And i just don't know whats going wrong.

for ($i = 0; $i <= 12; $i++) {
    $months[ucfirst(strftime("%B %G", strtotime( date( 'Y-m' )." +$i months")))] = ucfirst(strftime("%B %G", strtotime( date( 'Y-m' )." +$i months")));
    echo ucfirst(strftime("%B %G", strtotime( date( 'Y-m' )." +$i months")));
}

The echo output:

December 2015 Januari 2015 Februari 2016 Maart 2016 April 2016 Mei 2016 Juni 2016 Juli 2016 Augustus 2016 September 2016 Oktober 2016 November 2016 December 2016

Upvotes: 0

Views: 109

Answers (2)

Mihai Matei
Mihai Matei

Reputation: 24276

You can simply use:

$date = new DateTime('first day of this month');

for ($i = 0; $i < 13; $i++) {
    echo $date->format('F Y,');
    $date->modify('+1 month');
}

The output would be:

December 2015, January 2016, February 2016, March 2016, April 2016, May 2016, June 2016, July 2016, August 2016, September 2016, October 2016, November 2016, December 2016,

Upvotes: 2

Dezza
Dezza

Reputation: 1094

What about something like this?

<?php

$start = new DateTimeImmutable('first day of this month');
$interval = new DateInterval('P1M');
$period = new DatePeriod($start, $interval, 12);

foreach ($period as $date) {
    echo $date->format('F Y') . PHP_EOL;
}

Upvotes: 3

Related Questions