文章目錄
- bug重現
- 解決方法:用第三方插件來實現(不推薦原生代碼來實現)。項目中用的有dayjs。
- 若要自己實現,參考 AI給出方案:
bug重現
今天(2025-04-01)遇到的一個問題。原代碼邏輯大概是這樣的:
選擇一個日期,在這個日期的月份基礎上 加一個月。
let date = this.selectDate // 2025-03-31 08:00:00
let newDate = new Date(date.setMonth(date.getMonth() + 1))
console.log(newDate) // 2025-05-01 08:00:00
以上代碼理想中應該是 4月份對吧。可是輸出了5月1日。
原因是 4月沒有31日 導致setMonth后導致時間戳的時間溢出補到了日期中
底層邏輯可能是基于時間戳進行操作的。
Date原生的setMonth
指定是沒有判斷 月份天數。
解決方法:用第三方插件來實現(不推薦原生代碼來實現)。項目中用的有dayjs。
若要自己實現,參考 AI給出方案:
Date.prototype.mySetMonth = function(monthValue, dateValue) {// 獲取當前時間值let time = this.getTime();if (isNaN(time)) return NaN;// 分解日期let year = this.getFullYear();let day = this.getDate();let hours = this.getHours();let minutes = this.getMinutes();let seconds = this.getSeconds();let milliseconds = this.getMilliseconds();// 處理月份let month = Math.floor(Number(monthValue)); // 轉換為整數let yearAdjust = Math.floor(month / 12);let newMonth = month % 12;if (newMonth < 0) {newMonth += 12;yearAdjust--;}year += yearAdjust;// 如果提供了日期,則更新if (dateValue !== undefined) {day = Math.floor(Number(dateValue));}// 創建新日期let newDate = new Date(year, newMonth, day, hours, minutes, seconds, milliseconds);// 設置時間值this.setTime(newDate.getTime());// 返回時間戳return newDate.getTime();
};// 測試
let time = new Date('2025-03-31 08:00:00');
console.log(time); // "Mon Mar 31 2025 08:00:00"
time.mySetMonth(3); // 設置為 4 月
console.log(time); // "Wed Apr 30 2025 08:00:00"(自動調整到 30 日)