How to get the previous and next month?

前端 未结 8 733
旧巷少年郎
旧巷少年郎 2021-01-02 04:01
$year  = 2010;
$month = 10;

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

8条回答
  •  暖寄归人
    2021-01-02 04:06

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

提交回复
热议问题