5

I expected this functional to return 6/30/2005 instead of 7/1/2005.

print date("m/d/Y", strtotime("12/31/2004 +6 month"));

Similarly, print date("m/d/Y", strtotime("1/31/2011 +1 month")) returns 03/03/2011 while would like it to return 2/28/2011.

Does anyone know if there is a straight forward way to show the last day of the added month?

Anne
  • 26,765
  • 9
  • 65
  • 71
user1042425
  • 51
  • 1
  • 3

4 Answers4

6

How about this?

echo date("m/d/Y", strtotime("last day of 12/31/2004 + 6 month")); // 6/30/2005
echo date("m/d/Y", strtotime("last day of 1/31/2011 + 1 month")); // 2/28/2011

Demo

Edit: For your reference, here is a link to the documentation for relative times.

nickb
  • 59,313
  • 13
  • 108
  • 143
2

as strtotime continue in to next month if there isn't enoghe days that month, you can back 6 month and check if its end up on the start date

  $date2 = date("Y-m-d", strtotime("{$date} +6 months"));
  $date3 = date("Y-m-d", strtotime("{$date2} -6 months"));
  if($date3 != $date)
  {
     $date2 = date("Y-m-t", strtotime("{$date2} -1 months"));
  }

(or in your case "m/t/Y")

Puggan Se
  • 5,738
  • 2
  • 22
  • 48
0

One simple way is to actually go one month ahead of the day you want and then make the day value zero. Also, mktime() might be easier

$mymonth = 2;   // I want the last day of February
echo date('m/d/Y', mktime(0,0,0,$mymonth+1,0,2011));

This should return 2/28/2011.

anson
  • 4,156
  • 2
  • 22
  • 30
0

strtotime does the best it can with conflicting information. Saying

1/31/2011 +1month

would mean advancing to

2/31/2011

but February only has 28 (sometimes 29) days. 2011 isn't a leap year, so the "31st of February" gets normalized to "March 3rd".

The same applies for '12/31/2004 +6month'. That takes you to June 31st, 2005. But June only has 30 days, so the date is normalized to July 1st instead.

Marc B
  • 356,200
  • 43
  • 426
  • 500