常常會有人被strtotime結合-1 month, +1 month, next month的時候搞得很困惑, 而後就會以爲這個函數有點不那麼靠譜, 動不動就出問題. 用的時候就會很慌…ide
這不, 剛剛就有人在微博上又問我:函數
鳥哥,今天是2018-07-31 執行代碼:code
date("Y-m-d",strtotime("-1 month"))
怎麼輸出是2018-07-01?it
好的吧, 雖然這個問題看起來很迷惑, 但從內部邏輯上來講呢, 實際上是」對」的, 你先彆着急哈, 讓我慢慢講:微博
咱們來模擬下date內部的對於這種事情的處理邏輯:ast
var_dump(date("Y-m-d", strtotime("2017-06-31"))); //輸出2017-07-01
也就是說, 只要涉及到大小月的最後一天, 均可能會有這個迷惑, 咱們也能夠很輕鬆的驗證相似的其餘月份, 印證這個結論:class
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自動」規範化」: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
那若是是5.3以前的版本(還有人用麼?), 你可使用mktime之類的, 把全部的日子忽略掉, 好比都限定爲每個月1號就能夠了, 只不過就不如直接用first day來的更加優雅.im
如今, 搞清楚了內部原理, 是否是就不慌了?