toephu Posted March 30, 2010 Share Posted March 30, 2010 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 Quote Link to comment https://forums.phpfreaks.com/topic/197022-why-isnt-last-month-working/ Share on other sites More sharing options...
simshaun Posted March 30, 2010 Share Posted March 30, 2010 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? Quote Link to comment https://forums.phpfreaks.com/topic/197022-why-isnt-last-month-working/#findComment-1034284 Share on other sites More sharing options...
PFMaBiSmAd Posted March 30, 2010 Share Posted March 30, 2010 Because there is no corresponding day (the 30th) in February. Instead of using 'now', use the first day of the month (or at least a day that exists in all months.) Quote Link to comment https://forums.phpfreaks.com/topic/197022-why-isnt-last-month-working/#findComment-1034286 Share on other sites More sharing options...
toephu Posted March 30, 2010 Author Share Posted March 30, 2010 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 Quote Link to comment https://forums.phpfreaks.com/topic/197022-why-isnt-last-month-working/#findComment-1034301 Share on other sites More sharing options...
toephu Posted March 30, 2010 Author Share Posted March 30, 2010 nevermind i figured it out, i think this works: $curMonth=date('Y-M'); for ($i=11; $i >= 0; $i--) $months[] = date('Y-M',strtotime("$curMonth - $i month") ); Quote Link to comment https://forums.phpfreaks.com/topic/197022-why-isnt-last-month-working/#findComment-1034305 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.