increment date by one month

前端 未结 18 2445
广开言路
广开言路 2020-11-27 04:14

Let\'s say I have a date in the following format: 2010-12-11 (year-mon-day)

With PHP, I want to increment the date by one month, and I want the year to be automatica

18条回答
  •  孤城傲影
    2020-11-27 04:34

    (date('d') > 28) ? date("mdY", strtotime("last day of next month")) : date("mdY", strtotime("+1 month"));
    

    This will compensate for February and the other 31 day months. You could of course do a lot more checking to to get more exact for 'this day next month' relative date formats (which does not work sadly, see below), and you could just as well use DateTime.

    Both DateInterval('P1M') and strtotime("+1 month") are essentially blindly adding 31 days regardless of the number of days in the following month.

    • 2010-01-31 => March 3rd
    • 2012-01-31 => March 2nd (leap year)

提交回复
热议问题