PHP strtotime +1 month behaviour

前端 未结 8 2200
再見小時候
再見小時候 2020-11-30 10:10

I know about the unwanted behaviour of PHP\'s function

strtotime

For example, when adding a month (+1

8条回答
  •  悲哀的现实
    2020-11-30 10:35

    Somewhat similar to the Juhana's answer but more intuitive and less complications expected. Idea is like this:

    1. Store original date and the +n month(s) date in variables
    2. Extract the day part of both variables
    3. If days do not match, subtract number of days from the future date

    Plus side of this solution is that works for any date (not just the border dates) and it also works for subtracting months (by putting - instead of +). Here is an example implementation:

    $start = mktime(0,0,0,1,31,2015);
    for ($contract = 0; $contract < 12; $contract++) {
        $end = strtotime('+ ' . $contract . ' months', $start);
        if (date('d', $start) != date('d', $end)) { 
            $end = strtotime('- ' . date('d', $end) . ' days', $end);
        }
        echo date('d-m-Y', $end) . '|';
    }
    

    And the output is following:

    31-01-2015|28-02-2015|31-03-2015|30-04-2015|31-05-2015|30-06-2015|31-07-2015|31-08-2015|30-09-2015|31-10-2015|30-11-2015|31-12-2015|
    

提交回复
热议问题