$year = 2010;
$month = 10;
How do I get the previous month 2010-09
and next month 2010-11
?
$date = mktime( 0, 0, 0, $month, 1, $year );
echo strftime( '%B %Y', strtotime( '+1 month', $date ) );
echo strftime( '%B %Y', strtotime( '-1 month', $date ) );
try it like this:
$date = mktime(0, 0, 0, $month, 1, $year);
echo date("Y-m", strtotime('-1 month', $date));
echo date("Y-m", strtotime('+1 month', $date));
or, shorter, like this:
echo date("Y-m", mktime(0, 0, 0, $month-1, 1, $year));
echo date("Y-m", mktime(0, 0, 0, $month+1, 1, $year));
PHP is awesome in this respect, it will handle date overflows by correcting the date for you...
$PreviousMonth = mktime(0, 0, 0, $month - 1, 1, $year);
$CurrentMonth = mktime(0, 0, 0, $month, 1, $year);
$NextMonth = mktime(0, 0, 0, $month + 1, 1, $year);
echo '<p>Next month is ' . date('Ym', $NextMonth) .
' and previous month is ' . date('Ym', $PreviousMonth . '</p>';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With