Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is best solution to get next and previous month from given date php

Tags:

php

I want to get next and previous month from given date. this is my code.

$month = '2011-01-20';

$prevMOnth = funP($month); $nextMonth = funN($month);

what is best solution to do that.

like image 845
Dinuka Thilanga Avatar asked Dec 16 '22 04:12

Dinuka Thilanga


2 Answers

$next_month_ts = strtotime('2011-01-20 +1 month');
$prev_month_ts = strtotime('2011-01-20 -1 month');

$next_month = date('Y-m-d', $next_month_ts);
$prev_month = date('Y-m-d', $prev_month_ts);
like image 119
xdazz Avatar answered Apr 25 '23 15:04

xdazz


Code mentioned before might not work in the end of months with 31 day (or March): $prev_month_ts = strtotime('2011-01-20 -1 month');

This is a best solution to get name of previous month. Get this month first day's date, then subtract 1 day, then get month name:

date('F', strtotime('-1 day', strtotime(date('Y-m-01'))));

And get name of next month. Get this month last day's date, then add 1 day, then get month name:

date('F', strtotime('+1 day', strtotime(date('Y-m-t'))));
like image 34
ALeX inSide Avatar answered Apr 25 '23 15:04

ALeX inSide