Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: 2011-03-02 

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 date("Y-m")) in the most elegant manner as possible, which works for every day of the year? Optimal solution will be based on strtotime 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 strtotime-compatible string as input (to initialize internal date), and then allows date/time to be adjusted, also using strtotime-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 strtotime-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 
like image 665
mr.b Avatar asked Mar 30 '11 16:03

mr.b


People also ask

What is previous month?

previous month means the month or months immediately preceding the month for which a monthly report is due from qualified public depositories.

How can I get last date of previous month in PHP?

Get Last Day Of The Previous Month:$lastDay = date('t',strtotime('last month')); print_r($lastDay);


2 Answers

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'; $dt=date_create($datestring); echo $dt->format('Y-m'); //2011-02 
like image 172
dnagirl Avatar answered Sep 28 '22 08:09

dnagirl


if the day itself doesn't matter do this:

echo date('Y-m-d', strtotime(date('Y-m')." -1 month")); 
like image 24
ITroubs Avatar answered Sep 28 '22 09:09

ITroubs