作者: Angus.Fenying
日期: 2016-09-05 11:20 AM
今天遇到一個 Bug,是在逢 31 號當天,日曆控件(同事開發的)就會出問題。 表現爲凡是有 31 號的月份幾乎都不顯示 31 號,但是部分月份如 12 月和 7 月除外。
檢查代碼發現出錯的位置在於
//返回某月天數
function getDaysBayYearAndMonth(year, month) {
var date = new Date();
date.setFullYear(year);
date.setMonth(month);
date.setDate(0);
return date.getDate();
}
把系統時間設置爲 8 月 31 號,重啓瀏覽器,因爲是當天發現的。 從這個函數體開始單步調試,依次檢查,發現結果如下:
/**
* 調用函數 getDaysBayYearAndMonth(2016, 8)
*/
function getDaysBayYearAndMonth(year, month) {
var date = new Date(); // 2016-08-31
date.setFullYear(year); // 2016-08-31
date.setMonth(month); // 2016-10-01
date.setDate(0); // 2016-09-30
return date.getDate(); // 30
}
找到問題的關鍵所在了,因爲 setMonth
修改了月份爲 9 月,而 9 月沒有 31 號,遂自動進位到 10 月 1 日。
然後再設置 setDate(0)
使得返回上個月最後一天,變成了 9 月 30 日。
那 12 月和 7 月爲什麼沒有問題呢?因爲 7 月的下一個月是 8 月,而 12 月的下一個月是 1 月,1 月和 8 月都是有 31 號的。
問題遂解。