Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the previous and next month?

Tags:

date

php

$year  = 2010;
$month = 10;

How do I get the previous month 2010-09 and next month 2010-11?

like image 416
BRAVO Avatar asked Oct 14 '10 06:10

BRAVO


3 Answers

$date = mktime( 0, 0, 0, $month, 1, $year );
echo strftime( '%B %Y', strtotime( '+1 month', $date ) );
echo strftime( '%B %Y', strtotime( '-1 month', $date ) );
like image 180
poke Avatar answered Oct 31 '22 22:10

poke


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));
like image 31
oezi Avatar answered Oct 31 '22 22:10

oezi


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>';
like image 2
Fenton Avatar answered Oct 31 '22 21:10

Fenton