taebu
taebu

Reputation: 57

Adding 2 months in PHP

I've seen previous problems about adding two months to an existing date, however the existing answers do not help me much as I am getting different results than what I want. I have set up a date as follows:

$date = "2014-12-31";
$date = date('Y-m-d', strtotime("$date +2 month"));

After I've added 2 months, I print it:

echo $date;

My result:

2015-03-03

but this is not right to me because this is a full month beyond what I actually want:

2015-02-28

How can I do this?

Upvotes: 4

Views: 3200

Answers (2)

EternalHour
EternalHour

Reputation: 8661

I would use PHP's DateTime class.

$date = new DateTime('2014-12-31');
$date->modify('+2 month');
$date->format('Y-m-d');
echo $date;

It also depends on what you are expecting by 2 months, this can vary based on how many days in the month there are. Are you going by 30 days, 31 days, last day of month, first day of month?...etc.

Maybe you are looking for this,

$date = new DateTime('2014-12-31');
$date->modify('last day of +2 month');
$date->format('Y-m-d');
echo $date;

This may also help you. Relative Formats

Upvotes: 9

fortune
fortune

Reputation: 3382

You can use DateTime class and modify method argument like last day of second month

$date = new DateTime('2014-12-31');
$date->modify('last day of second month');
echo $date->format('Y-m-d');

Edit::

modify can have multiple possible arguments

last day of 2 month

last day of +2 month

Upvotes: 4

Related Questions