Forum Moderators: coopster
<?php
echo date("m/Y", strtotime("-1 month")); // returns 10/2006
?>
Instead it returned `10/2006` and upon further investigation strotime("-1 month") is actually just rolling back to day one of the current month.
<?php
echo date("m/d/Y", strtotime("-1 month")); // returns 10/1/2006
?>
I wasn't expecting this behavior, and it somewhat broke the logic of a "expired credit card" validation I had on one site. It's pretty disturbing that I completely missed this in testing. :/
if you create a date (i.e. a certain day, like 30.03.2005, for a calendar for example) for which you do not consider the time, when using mktime be sure to set the time of the day to noon:
strtotime("-1 month",mktime(12,0,0,1,31,2004));
?>
will cause troubles when calculating the relative time. It often is one day or even one month off... After I set the time to noon "strtotime" calculates as expected.
Also taken from there:
Just pointing out that date( 'M', strtotime( 'last month', [some timestamp]) ) will not actually give the name of the previous month if the day of [some timestamp] doesn't exsist in the previous month. It will instead round up, and give the name of one month AFTER the previous month ('this month', that is).
For example date( 'M', strtotime( 'last month', [March 31st]) ) will return 'Mar'.
This is documented here: [gnu.org...] (also linked from this manual page), but is not easy to find:
" The fuzz in units can cause problems with relative items. For example, `2003-07-31 -1 month' might evaluate to 2003-07-01, because 2003-06-31 is an invalid date. To determine the previous month more reliably, you can ask for the month before the 15th of the current month. For example:
$ date -R
Thu, 31 Jul 2003 13:02:39 -0700
$ date --date='-1 month' +'Last month was %B?'
Last month was July?
$ date --date="$(date +%Y-%m-15) -1 month" +'Last month was %B!'
Last month was June! "
What you can do is do it manually:
<?php
$month = 31 * 24 * 60 * 60; //not exactly last month, but 31 days earlier.
// 31 days; 24 hours; 60 minutes; 60 seconds
$lastMonth = date('Y-m-d', time() - $month);
?>
Regards
Michal
I see a problem with subtracting 31 days from the current date, then getting the month... Namely March 1st and 2nd would calculate the previous month as January (hopscotching right over the 28 day February).
But taking the idea of asking "for the month before the 15th of the current month" I think this code would work:
strtotime( "-1 month", mktime( 12, 0, 0, date("m"), 15, date("Y") ) );