Current Date is 29th March 2017
When I subtract 2 months using PHP and I get January
$prevmonth = date(\'M\', strtotime(\'-2 months\'));
As covered in the comments, there's no 29th Feb.
29th Feb becomes 1st March.
You may be better to get the current month number, -1 from it, and then get the textual representation.
$prevMonth = date('n') - 1;
$prevMonthText = date('M', mktime(0, 0, 0, $prevMonth, 10));
Or, you could use DateTime
if your PHP version allows (it should).
$prevMonth = date('n') - 1;
$dateObj = DateTime::createFromFormat('!m', $prevMonth);
$monthName = $dateObj->format('M'); // March
The only issue with this, that you might have spotted, is January will never return December. A quick ternary statement will catch that.
$prevMonth = ((date('n') - 1) < 1) ? 12 : date('n') - 1;
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.