Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP date returning wrong Month on subtracting one month

Tags:

date

php

Current Date is 29th March 2017

When I subtract 2 months using PHP and I get January

$prevmonth = date('M', strtotime('-2 months'));
echo $prevmonth;

But when I subtract 1 month it gives March

$prevmonth = date('M', strtotime('-1 months'));
echo $prevmonth;
like image 714
James Okpe George Avatar asked Nov 08 '22 00:11

James Okpe George


1 Answers

strtotime() uses 30 day months and there are only 28 in days in February (this year) so will not yield a valid date in February. You could use the current day d or j and subtract that which will always put you in the previous month (-29 days):

$prevmonth = date('M', strtotime('-' . date('d') . ' days'));

This will get December from January as well.

like image 179
AbraCadaver Avatar answered Nov 15 '22 11:11

AbraCadaver