user1042425
user1042425

Reputation: 51

php: strtotime("12/31/2004 +6 month")); not returning the last day of June

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?

Upvotes: 5

Views: 3148

Answers (4)

Marc B
Marc B

Reputation: 360702

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.

Upvotes: 0

Puggan Se
Puggan Se

Reputation: 5846

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")

Upvotes: 2

anson
anson

Reputation: 4164

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.

Upvotes: 0

nickb
nickb

Reputation: 59699

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.

Upvotes: 6

Related Questions