Adding 2 months to PHP

I have seen previous problems with adding two months to an existing date, however the existing answers do not help me because I have different results than what I want. I set the date like this:

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

      

After I added 2 months, I print it:

echo $date;

      

My result:

2015-03-03

but this is not right for me because this is a full month outside of what I really want:

2015-02-28

How can i do this?

+3


source to share


2 answers


You can use class argument DateTime

and change method method likelast 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

may have several possible arguments

last day of 2 months

last day +2 months

+4


source


I would use the PHP 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 for 2 months, it can vary depending on how many days in the month there are. Are you going for 30 days, 31 days, the last day of the month, the first day of the month? ... etc.



You may be looking for this,

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

      

It might also help you. Relative formats

+5


source







All Articles