萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript Date.setMonth() 方法:設置月份(0-11 陷阱)

Date.setMonth() 方法簡介

Date.prototype.setMonth() 根據**本地時間**設置 Date 對象的**月份**,可選同時設置日期。返回更新後的時間戳(毫秒數)。

語法

dateObj.setMonth(monthIndex[, dayValue])

參數詳解

參數範圍說明
monthIndex0-11**必填**。**0=一月,11=十二月**(核心陷阱!)
dayValue1-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

⚠️ 核心陷阱:月份 0 基索引

// ❌ 錯誤:以為 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());

實戰應用場景

1. 月份選擇器同步

<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);
});

2. 獲取某月天數(巧用自動進位)

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

3. 日期運算:加減月份

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;
}

UTC 版本:setUTCMonth()

const dt = new Date();
dt.setUTCMonth(5, 15); // 設置 UTC 6月15日
console.log(dt.toISOString());

注意事項

  • 返回時間戳:不可鏈式調用 Date 方法
  • 月份 0-11:**永遠記住**,封裝工具函數統一轉換
  • 日期參數可選:不傳保持原日期,但若原日期在目標月不存在(如 1月31日 → 2月),會自動進位
  • 批量修改:多次調用 setMonth/setDate 會多次重算時間戳,建議計算好目標年月日後一次性 new Date(y, m, d)

現代替代:Temporal API (提案)

// 未來:PlainDateTime.with({ month: 3 }) // 1-12 直觀、不可變

setMonth() 核心在於**月份 0 基索引**與**自動進位**。封裝統一「1-12 月」的工具函數,能消除 90% 的月份相關 Bug。

copyright © 萬盛學電腦網 all rights reserved