strtotime 踩坑記錄

cnguu發表於2019-12-31

前言

今天是 2019 年的最後一天,即將從 2019 年鹹魚進化成 2020 年鹹魚

就在今早,程式碼寫著寫著就出現了一個奇怪的事情:


echo  date('Y/m/d', strtotime('-1 month'));

// 2019/12/01

見鬼了,還能不能好好讓我當一條鹹魚了?


echo  date('Y/m/d', strtotime('-2 month'));

// 2019/10/31

唔。。。來看看鳥哥怎麼說:令人困惑的 strtotime

date 內部處理邏輯

  • 先做 -1 month :今天是 2019/12/31,上個月的今天就是 2019/11/31

  • 再做日期規範化:因為 11 月沒有 31 號,自然成了 12 月的 1 號

驗證一下:


echo  date('Y/m/d', strtotime('-1 month', strtotime('2019/03/31')));

// 2019/03/03

那我該如何獲取上個月的最後一天日期呢?

相對格式


echo  date('Y/m/d', strtotime('last day of -1 month'));

// 2019/11/30

相對格式

最後

問題解決,繼續當回一條可愛的鹹魚。

原文

本作品系原創(除文中說明外), 採用《CC 協議》許可,轉載必須註明作者和本文連結

相關文章