萬盛學電腦網

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

解決 IE8 不支援 new Date('YYYY-MM-DD') 的日期差計算相容寫法

問題背景

IE8 不支援 ISO 8601 格式的 new Date('2012-11-10'),會回傳 NaN。需手動解析年月日再建立 Date 物件,以計算兩日期相差天數。

相容寫法(支援 IE8+ 及所有現代瀏覽器)

/**
 * 計算兩個日期字串 (YYYY-MM-DD) 相差天數
 * @param {string} strDateStart 開始日期
 * @param {string} strDateEnd   結束日期
 * @returns {number} 相差天數(正整數)
 */
function getDays(strDateStart, strDateEnd) {
    const separator = "-";
    const d1 = strDateStart.split(separator).map(Number); // [year, month, day]
    const d2 = strDateEnd.split(separator).map(Number);

    // month 為 0-based (0=1月)
    const date1 = new Date(d1[0], d1[1] - 1, d1[2]);
    const date2 = new Date(d2[0], d2[1] - 1, d2[2]);

    const diffMs = Math.abs(date1 - date2); // 毫秒差
    return Math.floor(diffMs / (1000 * 60 * 60 * 24));
}

// 測試
console.log(getDays("2012-11-10", "2012-11-15")); // 5
console.log(getDays("2023-01-01", "2023-12-31")); // 364

關鍵點解析

  • new Date(year, monthIndex, day):月份為 0-11,故需 -1。
  • 使用 map(Number) 將字串陣列轉數值,避免字串相減隱式轉型錯誤。
  • Math.abs 確保無論先後順序皆為正數天數。
  • 不含時間部分,若需精確到時分秒,傳入完整參數 new Date(y, m, d, h, mi, s)。

現代瀏覽器簡寫(不需支援 IE8)

const daysBetween = (a, b) => Math.abs(new Date(a) - new Date(b)) / 864e5; // 864e5 = 86400000ms

延伸:Date.parse 相容性補充

// 另一種相容寫法:手動拼接為 Date.parse 支援的格式
function parseDateIE8(str) {
    // '2012-11-10' -> '2012/11/10' (IE8 支援斜線格式)
    return new Date(Date.parse(str.replace(/-/g, '/')));
}

最佳實踐建議

  1. 專案若已引入 date-fns、Day.js 或 Moment.js,直接用庫函數統一處理,避免手寫解析 Bug。
  2. 後端傳輸日期建議使用 ISO 8601 字串(2023-11-10T00:00:00Z)或 Unix Timestamp(毫秒數),前端統一 new Date(timestamp) 最穩健。
  3. 若必須在 IE8 運行,建議引入 es5-shim + es6-shim 並封裝統一日期工具模組。
copyright © 萬盛學電腦網 all rights reserved