BRAVO
BRAVO

Reputation: 233

How to get the previous and next month?

$year  = 2010;
$month = 10;

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

Upvotes: 11

Views: 14002

Answers (8)

Limitless isa
Limitless isa

Reputation: 3802

 setlocale(LC_TIME,"turkish");
 $Currentmonth=iconv("ISO-8859-9","UTF-8",strftime('%B'));
 $Previousmonth=iconv("ISO-8859-9","UTF-8",strftime('%B',strtotime('-1 MONTH')));
 $Nextmonth=iconv("ISO-8859-9","UTF-8",strftime('%B',strtotime('+1 MONTH')));

echo $Previousmonth; // Şubat /* 2017-02 */
echo $Currentmonth; // Mart /* 2017-03 */
echo $Nextmonth; // Nisan /* 2017-04 */

Upvotes: 0

Nisanth Thulasi
Nisanth Thulasi

Reputation: 1

     echo date('Y-m-d', strtotime('next month'));

Upvotes: 0

oezi
oezi

Reputation: 51817

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));

Upvotes: 4

Wasim Karani
Wasim Karani

Reputation: 8886

strftime *:-* Format the time and/or date according to locale settings. Month and weekday names and other language-dependent strings respect the current locale set with setlocale().

strftime( '%B %Y', strtotime( '+1 month', $date ) );
strftime( '%B %Y', strtotime( '-1 month', $date ) );

Upvotes: 0

Fenton
Fenton

Reputation: 251232

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>';

Upvotes: 2

codaddict
codaddict

Reputation: 455380

You can just add 1 to the current month and then see if you crossed the year:

$next_year  = $year;
$next_month = ++$month;

if($next_month == 13) {
  $next_month = 1;    
  $next_year++;
}

Similarly for previous month you can do:

$prev_year  = $year;
$prev_month = --$month;

if($prev_month == 0) {
  $prev_month = 12;
  $prev_year--;
}

Upvotes: 1

user180100
user180100

Reputation:

$prevMonth = $month - 1;
$nextMonth = $month + 1;
$prevYear = $year;
$nextYear = $year;

if ($prevMonth < 1) {
    $prevMonth = 1;
    $prevYear -= 1;
}

if ($nextMonth > 12) {
    $nextMonth = 1;
    $nextYear += 1
}

or

// PHP > 5.2.0
$date = new DateTime();
$date->setDate($year, $month, 1);
$prevDate = $date->modify('-1 month');
$nextDate = $date->modify('+1 month');
// some $prevDate->format() and $nextDate->format() 

Upvotes: 1

poke
poke

Reputation: 388313

$date = mktime( 0, 0, 0, $month, 1, $year );
echo strftime( '%B %Y', strtotime( '+1 month', $date ) );
echo strftime( '%B %Y', strtotime( '-1 month', $date ) );

Upvotes: 20

Related Questions