Date.prototype.setMonth() 根據**本地時間**設置 Date 對象的**月份**,可選同時設置日期。返回更新後的時間戳(毫秒數)。
dateObj.setMonth(monthIndex[, dayValue])
| 參數 | 範圍 | 說明 |
|---|---|---|
monthIndex | 0-11 | **必填**。**0=一月,11=十二月**(核心陷阱!) |
dayValue | 1-31 | 可選。日期。若提供,月份會先設置,再設置日期 |
更新後的時間戳(Number),非 Date 對象。
const dt = new Date('Aug 28, 2008 23:30:00'); // 8月28日
console.log('原始:', dt.toString()); // Thu Aug 28 2008 23:30:00 GMT+0800
// 設置為 3月 (monthIndex=2)
dt.setMonth(2);
console.log('setMonth(2):', dt.toString()); // Fri Mar 28 2008 23:30:00 GMT+0800
// 同時設置月份和日期
dt.setMonth(11, 25); // 12月25日
console.log('setMonth(11,25):', dt.toString()); // Thu Dec 25 2008 23:30:00 GMT+0800
// ❌ 錯誤:以為 1=一月
new Date(2024, 1, 1); // 2024-02-01 (二月!)
// ✅ 正確:0=一月
new Date(2024, 0, 1); // 2024-01-01
// 封裝安全函數
function createDate(year, month1to12, day) {
return new Date(year, month1to12 - 1, day);
}
參數超出範圍自動調整高位:
const dt = new Date(2024, 0, 1); // 1月1日
dt.setMonth(12); // 月份 12 → 翌年 1月
console.log(dt.getFullYear(), dt.getMonth()); // 2025 0 (1月)
dt.setMonth(-1); // 月份 -1 → 上年 12月
console.log(dt.getFullYear(), dt.getMonth()); // 2024 11 (12月)
dt.setMonth(1, 32); // 2月32日 → 3月3日 (或 2月31日→3月2日,視閏年)
console.log(dt.toString());
<select id="monthSelect">
<option value="0">一月</option> ... <option value="11">十二月</option>
</select>
$('#monthSelect').on('change', function() {
const date = new Date(); // 當前日期
date.setMonth(+this.value); // 保持年、日不變
updateCalendar(date);
});
function getDaysInMonth(year, month1to12) {
// 下月 1 日 的 0點 - 1毫秒 = 本月最後一天
const nextMonth = new Date(year, month1to12, 1); // month1to12 作為月份索引 (1月=0...12月=11? 這裡傳 12 會進位到翌年)
// 更清晰寫法:
return new Date(year, month1to12, 0).getDate(); // day=0 表示上月最後一天
}
console.log(getDaysInMonth(2024, 2)); // 29 (閏年二月)
console.log(getDaysInMonth(2023, 2)); // 28
function addMonths(date, months) {
const d = new Date(date); // 複製
const targetMonth = d.getMonth() + months;
d.setMonth(targetMonth); // 自動處理跨年
// 處理「31號加一個月」變成「下月31號不存在」的問題
// setMonth 會自動進位到下月 1、2、3號
// 如需保持「月末」,需額外邏輯
return d;
}
// 保持月末特性
function addMonthsKeepEndOfMonth(date, months) {
const d = new Date(date);
const isEndOfMonth = d.getDate() === new Date(d.getFullYear(), d.getMonth()+1, 0).getDate();
d.setMonth(d.getMonth() + months);
if (isEndOfMonth) {
d.setDate(0); // 設置為當月最後一天
}
return d;
}
const dt = new Date();
dt.setUTCMonth(5, 15); // 設置 UTC 6月15日
console.log(dt.toISOString());
new Date(y, m, d)// 未來:PlainDateTime.with({ month: 3 }) // 1-12 直觀、不可變
setMonth() 核心在於**月份 0 基索引**與**自動進位**。封裝統一「1-12 月」的工具函數,能消除 90% 的月份相關 Bug。