note 42840 added to function.strtotime
| From: | SandroBilbeisi | Date: | Mon, 31 May 2004 18:25:52 +0000 |
| Subject: | note 42840 added to function.strtotime | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-70356@lists.php.net to get a copy of this message | ||
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...
----
Manual Page -- http://www.php.net/manual/en/function.strtotime.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+42840
Delete -- http://master.php.net/manage/user-notes.php?action=delete+42840&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+42840&report=yes
Search -- http://master.php.net/manage/user-notes.php