How to get the previous and next month?

前端 未结 8 750
旧巷少年郎
旧巷少年郎 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:14

    $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() 
    

提交回复
热议问题