Jump to content

why isn't last month working?


toephu

Recommended Posts

Today is March 30th, 2010, why is it then when I run this code it outputs "2010-Mar"?

echo date('Y-M',strtotime("now - 1 month"));

then i try

echo date('Y-M',strtotime("now - 2 month"));

and it outputs "2010-Jan" however it seems to be skipping february..

 

i have this following code to print out the previous 12 months, it was working up until a few days ago i noticed it output March twice, it is skipping feb..

for ($i=11; $i >= 0; $i--)
$months[] = date('Y-M',strtotime("now - $i month") ); //build array of last 12 months

 

any ideas?

 

thanks

-TP

Link to comment
https://forums.phpfreaks.com/topic/197022-why-isnt-last-month-working/
Share on other sites

If you output Y-m-d you will see what its doing. March 30th - 1 month is not February 30th obviously, because its an invalid date. So what it does is subtract the maximum days of the previous month (28 this year) from March 30th, giving you March 2nd.  What would you expect it to do?

i want to keep my code simple. is there an easy way to get the first day of each month?

or basically what is the cleanest way to fix this code so it outputs the months correctly? since using "now - $i months" isn't always going to work..

for ($i=11; $i >= 0; $i--)
$months[] = date('Y-M',strtotime("now - $i month") );

 

thanks for the quick responses

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.