來自PHP的strtotime函數的坑
問題描述
今天,我手邊某個外包的Case收到客戶的友善回報,當用戶希望將某個日期的預約時間移動到下個月或者提前一個月時,有時候會發生跟預期的結果的不同,最終將問題定位在strtotime這個函數上。
問題重現
$reservation_date = "2019-09-05";
var_dump(date("Y-m-d", strtotime("-1 month", strtotime($reservation_date)))); //2019-08-05-如預期
$reservation_date = "2019-09-05";
var_dump(date("Y-m-d", strtotime("+1 month", strtotime($reservation_date)))); //2019-10-05-如預期
$reservation_date = "2019-08-31";
var_dump(date("Y-m-d", strtotime("-1 month", strtotime($reservation_date)))); //2019-07-31-如預期
$reservation_date = "2019-07-31";
var_dump(date("Y-m-d", strtotime("-1 month", strtotime($reservation_date)))); //2019-07-01
$reservation_date = "2019-03-31";
var_dump(date("Y-m-d", strtotime("-1 month", strtotime($reservation_date)))); //2019-03-03
$reservation_date = "2016-03-31";
var_dump(date("Y-m-d", strtotime("-1 month", strtotime($reservation_date)))); //2016-03-02