PHP strtotime +1 month behaviour

前端 未结 8 2199
再見小時候
再見小時候 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:42

    Had the same issue recently and ended up writing a class that handles adding/subtracting various time intervals to DateTime objects.
    Here's the code:
    https://gist.github.com/pavlepredic/6220041#file-gistfile1-php
    I've been using this class for a while and it seems to work fine, but I'm really interested in some peer review. What you do is create a TimeInterval object (in your case, you would specify 1 month as the interval) and then call addToDate() method, making sure you set $preventMonthOverflow argument to true. The code will make sure that the resulting date does not overflow into next month.

    Sample usage:

    $int = new TimeInterval(1, TimeInterval::MONTH);
    $date = date_create('2013-01-31');
    $future = $int->addToDate($date, true);
    echo $future->format('Y-m-d');
    

    Resulting date is: 2013-02-28

提交回复
热议问题