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.
$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);
don't know if it's the best way to do it, but it's built into php, check out strtotime
EDIT: sample code
$month = '2011-01-20';
$timestamp = strtotime ("+1 month",strtotime ($month));
$nextMonth = date("Y-m-d",$timestamp);
$date = "2012-01-25";
$priormonth = date ('m', strtotime ( '-1 month' , strtotime ( $date )));
$futuremonth = date ('m', strtotime ( '+1 month' , strtotime ( $date )));
echo $priormonth; // this will equal 12
echo "<br/>";
echo $futuremonth; // this will equal 02
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'))));
The '-1 month' solution is unreliable when the month has 31 days (like ALeX inSide mentioned). Here is a function that returns the date of any desired number of months before a given date: (it returns actually the 1st day's date)
function getAnyPreviousMonthDate( $monthsBefore = null, $startDate = null )
{
$monthsBefore = $monthsBefore ?? 1; //php7
$monthsBefore = abs($monthsBefore);
$c = $startDate ?? date('Y-m-d');
for($i==0; $i<$monthsBefore; $i++) {
$c = date('Y-m-d', strtotime('first day of previous month '.$c));
}
return $c;
}
so if we calle this like:
echo getAnyPreviousMonthDate(3);
// we will get the first day of past 3 months from now
echo getAnyPreviousMonthDate(1, '2015-10-31');
// will return: '2015-09-01'