4

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?

sjagr
  • 15,983
  • 5
  • 40
  • 67
taebu
  • 57
  • 2
  • 8

2 Answers2

9

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

EternalHour
  • 8,308
  • 6
  • 38
  • 57
  • i tried this code but. Catchable fatal error: Object of class DateTime could not be converted to string in /home/hosting_users/cashq/www/test/strtotime.php on line 14 this error code to fix how to do that? – taebu Dec 31 '14 at 04:04
  • Seems that you are doing something different than what I posted. – EternalHour Dec 31 '14 at 04:07
  • DateTime is an object, but the format method will return a string which you can echo. E.g., you can use the following: `echo $date->format('Y-m-d');` – David Dec 31 '14 at 04:15
  • thanks to @David and @EternalHour datetime class used for Success. but this result same `$date = new DateTime('2014-12-31'); $date->modify('+2 month'); //$date->format('Y-m-d'); echo "
    "; echo $date->format('Y-m-d');` **2015-03-03** what's wrong???
    – taebu Dec 31 '14 at 04:24
  • @taebu look at my comment under your question. – EternalHour Dec 31 '14 at 04:25
4

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

Community
  • 1
  • 1
fortune
  • 3,361
  • 1
  • 20
  • 30