Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

strtotime

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?

like image 202
user1042425 Avatar asked Nov 11 '11 20:11

user1042425


2 Answers

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.

like image 140
nickb Avatar answered Nov 17 '22 04:11

nickb


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

like image 2
Puggan Se Avatar answered Nov 17 '22 05:11

Puggan Se