Catch date of the next 12 months with php

Asked

Viewed 361 times

0

Good evening people, as I can do, to catch the 1° day of each month, counting as start the date of today, and catching 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'));

What it would be like to catch the next 12?

1 answer

1


With Datetime

Use DateTime to catch one month at a time in a loop I use ::modify() 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);

Upshot:

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 is going to get 13 months actually, because we’ve already started with the first month, since you said:

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

But if you want to take from next month count the 12 months then change this to 11 o for:

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

Sem Datetime

Although I don’t think I would even need this, after all if it is the first day would suffice to "enumerate" with an array adding up the month, when it passes from 12 back to month 1 and sums up 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);
  • 1

    Very good, helped a lot. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.