mr.b mr.b -4 years ago 283
PHP Question

How to get previous month and year relative to today, using strtotime and date?

I need to get previous month and year, relative to current date.

However, see following example.

// Today is 2011-03-30
echo date('Y-m-d', strtotime('last month'));

// Output:

This behavior is understandable (to a certain point), due to different number of days in february and march, and code in example above is what I need, but works only 100% correctly for between 1st and 28th of each month.

So, how to get last month AND year (think of
) in the most elegant manner as possible, which works for every day of the year? Optimal solution will be based on
argument parsing.

Update. To clarify requirements a bit.

I have a piece of code that gets some statistics of last couple of months, but I first show stats from last month, and then load other months when needed. That's intended purpose. So, during THIS month, I want to find out which month-year should I pull in order to load PREVIOUS month stats.

I also have a code that is timezone-aware (not really important right now), and that accepts
-compatible string as input (to initialize internal date), and then allows date/time to be adjusted, also using
-compatible strings.

I know it can be done with few conditionals and basic math, but that's really messy, compared to this, for example (if it worked correctly, of course):

echo tz::date('last month')->format('Y-d')

So, I ONLY need previous month and year, in a
-compatible fashion.

Answer (thanks, @dnagirl):

// Today is 2011-03-30
echo date('Y-m-d', strtotime('first day of last month')); // Output: 2011-02-01

Answer Source

Have a look at the DateTime class. It should do the calculations correctly and the date formats are compatible with strttotime. Something like:

$datestring='2011-03-30 first day of last month';
echo $dt->format('Y-m'); //2011-02
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download