經(jīng)常會(huì)有人被strtotime結(jié)合-1 month, +1 month, next month的時(shí)候搞得很困惑, 然后就會(huì)覺(jué)得這個(gè)函數(shù)有點(diǎn)不那么靠譜, 動(dòng)不動(dòng)就出問(wèn)題. 用的時(shí)候就會(huì)很慌...
比如:
date("Y-m-d",strtotime("+1 month"))
當(dāng)前時(shí)間是 3 .31,加一個(gè)月應(yīng)該是 4.31,但是由于4 月沒(méi)有 31 號(hào),在對(duì)日期規(guī)范化后得到的就是 5 月 1 號(hào)了。
也就是說(shuō), 只要涉及到大小月的最后一天, 都可能會(huì)有這個(gè)迷惑, 我們也可以很輕松的驗(yàn)證類(lèi)似的其他月份, 印證這個(gè)結(jié)論:
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開(kāi)始呢, date新增了一系列修正短語(yǔ), 來(lái)明確這個(gè)問(wèn)題, 那就是"first day of" 和 "last day of", 也就是你可以限定好不要讓date自動(dòng)"規(guī)范化":
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 轉(zhuǎn)換成我們想要的格式。
使用第三方類(lèi)Carbon,
我們打開(kāi)源碼發(fā)現(xiàn)也是繼承了**DateTime **:

image-20200401134013806
它有個(gè)方法,可以直接加一個(gè)月,addMonthNoOverflow,點(diǎn)進(jìn)去看源碼;
/**
* Add a month with no overflow to the instance
*
* @param int $value
*
* @return static
*/
public function addMonthNoOverflow($value = 1)
{
return $this->addMonthsNoOverflow($value);
}
再點(diǎn)進(jìn)去發(fā)現(xiàn),他其實(shí)也是利用的 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;
}