note 42840 rejected from function.strtotime by betz

From: Date: Mon, 31 May 2004 18:32:49 +0000
Subject: note 42840 rejected from function.strtotime by betz
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-70357@lists.php.net to get a copy of this message
Note Submitter: Sandro Bilbeisi <sandrino68@libero.it> ---- There seems to be a bug in the 'strtotime' function, with regard to month arithmetic (at beginning or end of month): for example: $myDateTime=mktime(0,0,0,5,31,2004); // May 31 2004 echo date("F j, Y",strtotime("-2 month",$myDateTime)); // March 31, 2004 (OK) echo date("F j, Y",strtotime("-1 month",$myDateTime)); // May 1, 2004 (What the !?%#!!) echo date("F j, Y",strtotime("+-0 month",$myDateTime)); // May 31, 2004 (OK) echo date("F j, Y",strtotime("+1 month",$myDateTime)); // July 1, 2004 (What the !?%#!!) There is a boundary check error ! My Workaround: first calculate with a 'median' value for the day in the month (15 is ok). this will reduce the probability of month boundary errors to zero. $currx_day='31'; // ignored initially, used to patch up at end $currx_year = '2004'; $currx_month = '5'; $currMedian=mktime(0,0,0,$currx_month,15,$currx_year); // May 15 2004 // echo date("F j, Y",strtotime("-2 month",$currMedian)); // March 15, 2004 (OK) echo date("F j, Y",strtotime("-1 month",$currMedian)); // April 15, 2004 (OK echo date("F j, Y",strtotime("+-0 month",$currMedian)); // May 31, 2004 (OK) echo date("F j, Y",strtotime("+1 month",$currMedian)); // June 15, 2004 (OK) // at this point you can replace the median day with the real day you wanted originally (paying attention to avoid assigning invalid days to months (eg no Feb 30th) $newDate= strtotime("-3 month",$currMedian); // eg. february $daysInMonth = date("t",$newDate); if($currx_day > $daysInMonth){ $newday= $daysInMonth; // don't exceed month's maximum } else { $newday= $currx_day; // original day } sorry if it's a little convoluted, but it works...

« previous php.notes (#70357) next »