Add a date and an x number of months

1

My first post here, so if you enter something wrong, I apologize.

My problem is this: I use a method in PHP to add a date with a x number of months . For example:

2017-01-01 + 11 months

Expected result:

2017-12-01 .

But I need something that besides bringing the added month, which also brings the last day of the month.

For example:

2017-01-0 + 11 meses = 2017-12-31 .

Do you realize that the number of days came with the last day of the month of December together? So I need it.

% w / w% will always start with day 01, regardless of the year / month that will be searched.

I'm currently using this code to add up the number of months with the date:

public static function SomarDataMes($data, $meses){

   $data = explode("/", $data);

   $newData = date("d/m/Y", mktime(0, 0, 0, $data[1] + $meses, $data[0], $data[2]) );

   return $newData;

 }
    
asked by anonymous 20.12.2017 / 18:22

1 answer

2

In a way, it's simple. Following the logic: Sum the amount of months, just after the last day of the month.

// Data de ínicio 
$date    = (new DateTime('2017-10-01'));

// Adiciona 2 meses a data
$newDate = $date->add(new DateInterval('P2M')); 

// Altera a nova data para o último dia do mês
$lDayOfMonth = $newDate->modify('last day of this month');


echo $lDayOfMonth->format('Y-m-d'); // 2017-12-31

Example: link

    
20.12.2017 / 18:39