Get date of the next 12 months with php

0

Good evening people, as I can do, to pick up the 1st day of each month, counting the beginning of today's date, and taking the next day 01/08/2018 and the next 12 months.

Try this code:

$firstDayNextMonth = date('Y-m-d', strtotime('first day of next month'));

How would you get the next 12?

    
asked by anonymous 23.07.2018 / 22:18

1 answer

1

With DateTime

If you use DateTime to get one month at a time in a loop I use ::modify() you can extract, for example:

<?php

$dt = new DateTime('first day of next month');

$datas = array( $dt->format('Y-m-d') );

for ($i = 0; $i < 12; $i++) {
    $dt->modify('+1 month');

    $datas[] = $dt->format('Y-m-d');
}

print_r($datas);

Result:

Array
(
    [0] => 2018-08-01
    [1] => 2018-09-01
    [2] => 2018-10-01
    [3] => 2018-11-01
    [4] => 2018-12-01
    [5] => 2019-01-01
    [6] => 2019-02-01
    [7] => 2019-03-01
    [8] => 2019-04-01
    [9] => 2019-05-01
    [10] => 2019-06-01
    [11] => 2019-07-01
    [12] => 2019-08-01
)

This will actually take 13 months, since we started with the first month, since you said:

  

and catching the next day 08/01/2018 and the next 12 months.

But if you want to get it from the next month count the 12 months then change it to 11 for :

for ($i = 0; $i < 11; $i++) {

No DateTime

Although I do not think I would need this, after all, if it's the first day, just enumerate an array by adding the month, when it goes from 12 to month 1 and adds the year:

<?php

$j = count($meses);
$ano = date('Y');
$mes = date('m');
$datas = array();

for ($i = 0; $i < 12; $i++) {
    $mes++;

    if ($mes > 12) {
       $mes = 1;
       $ano++;
    }

    $datas[] = sprintf('%04d-%02d-01', $ano, $mes);
}

print_r($datas);
    
23.07.2018 / 22:38