I need to get the previous month and year relative to the current date.
However, see the following example.
// Today is 2011-03-30 echo date('Ym-d', strtotime('last month')); // Output: 2011-03-02
This behavior is understandable (to a certain point) due to the different number of days in February and March, and the code in the above example is what I need, but it only works 100% correctly between the 1st and 28th of each month.
So, how to get the last month AND year (think of date("Ym") ) in the most elegant way that works every day of the year? The optimal solution will be based on the analysis of strtotime arguments.
Update To clarify the requirements a bit.
I have a piece of code that receives statistics for the last few months, but first I show statistics for the last month, and then load the other months when necessary. This is the intended goal. So, during this month I want to find out which month-year I have to pull in order to download the PREVIOUS monthly statistics.
I also have code that is related to the time zone (this is not really important right now), and accepts the strtotime string as input (to initialize the internal date), and then allows the date / time to be adjusted, also using strtotime -connected strings.
I know that this can be done with a few conditional expressions and basic math, but it is really messy compared to this, for example (if it works correctly, of course):
echo tz::date('last month')->format('Y-d')
So, I ONLY need the previous month and year, in a strtotime compatible way.
Answer (thanks, @dnagirl):
// Today is 2011-03-30 echo date('Ym-d', strtotime('first day of last month')); // Output: 2011-02-01