- 問題輸出
使用strtotime獲取大小月的最後一天
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