Sum a date and a number x of months

Asked

Viewed 3,137 times

2

My first post here, so if you type anything wrong, I apologize.

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

2017-01-01 + 11 months

expected result:

2017-12-01.

But I need something that besides bringing the month together, that 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 December month together? So, I need this.

To $data1 will always start with day 01, regardless of the year/month that will be sought.

I am currently using this code to add the number of months to 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;

 }

2 answers

3

In a way, it’s simple. Following the logic: Add up the amount of months, soon after catch 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: http://sandbox.onlinephpfunctions.com/code/c1b428e66c70a7b2129f9153aba4b256d62b779b

-1

$date = '2017-01-01';
$months = 11;
$frequency = [
    'DAY',
    'MONTH',
    'YEAR'
];
print date("Y-m-d", strtotime($date. "+".$months." ".$frequency['0']));

Browser other questions tagged

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