经常会有人被 strtotime 结合 – 1 month, +1 month, next month 的时候搞得很困惑,然后就会觉得这个函数有点不那么靠谱,动不动就出问题。用的时候就会很慌…

比如:

date("Y-m-d",strtotime("+1 month"))

当前时间是 3 .31, 加一个月应该是 4.31,但是由于 4 月没有 31 号,在对日期规范化后得到的就是 5 月 1 号了。

也就是说,只要涉及到大小月的最后一天,都可能会有这个迷惑,我们也可以很轻松的验证类似的其他月份,印证这个结论:

var_dump(date("Y-m-d", strtotime("-1 month", strtotime("2017-03-31"))));
//输出2017-03-03
var_dump(date("Y-m-d", strtotime("+1 month", strtotime("2017-08-31"))));
//输出2017-10-01
var_dump(date("Y-m-d", strtotime("next month", strtotime("2017-01-31"))));
//输出2017-03-03
var_dump(date("Y-m-d", strtotime("last month", strtotime("2017-03-31"))));
//输出2017-03-03

那怎么办呢?

从 PHP5.3 开始呢,date 新增了一系列修正短语,来明确这个问题,那就是”first day of” 和 “last day of”, 也就是你可以限定好不要让 date 自动” 规范化”:

var_dump(date("Y-m-d", strtotime("last day of -1 month", strtotime("2017-03-31"))));
//输出2017-02-28
var_dump(date("Y-m-d", strtotime("first day of +1 month", strtotime("2017-08-31"))));
////输出2017-09-01
var_dump(date("Y-m-d", strtotime("first day of next month", strtotime("2017-01-31"))));
////输出2017-02-01
var_dump(date("Y-m-d", strtotime("last day of last month", strtotime("2017-03-31"))));
////输出2017-02-28

还有一种方法,使用 DateTime:

$d = new DateTime( '2020-03-31' );
$d->modify( 'first day of next month' );
echo $d->format("Y-m-d"); 

同样的也是支持 first day of 以及 last day of ,最后 format 转换成我们想要的格式。

使用第三方类 Carbon,
我们打开源码发现也是继承了 DateTime

它有个方法,可以直接加一个月,addMonthNoOverflow, 点进去看源码;

/**
     * Add a month with no overflow to the instance
     *
     * @param int $value
     *
     * @return static
     */
    public function addMonthNoOverflow($value = 1)
    {
        return $this->addMonthsNoOverflow($value);
    }

再点进去发现,他其实也是利用的 last day of

 /**
     * Add months without overflowing to the instance. Positive $value
     * travels forward while negative $value travels into the past.
     *
     * @param int $value
     *
     * @return static
     */
    public function addMonthsNoOverflow($value)
    {
        $day = $this->day;

        $this->modify((int) $value.' month');

        if ($day !== $this->day) {
            $this->modify('last day of previous month');
        }

        return $this;
    }

————————————————
原文作者:wacho
转自链接:https://learnku.com/articles/42720
版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请保留以上作者信息和原文链接。

By cc

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注