IE8 不支援 ISO 8601 格式的 new Date('2012-11-10'),會回傳 NaN。需手動解析年月日再建立 Date 物件,以計算兩日期相差天數。
/**
* 計算兩個日期字串 (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)。const daysBetween = (a, b) => Math.abs(new Date(a) - new Date(b)) / 864e5; // 864e5 = 86400000ms
// 另一種相容寫法:手動拼接為 Date.parse 支援的格式
function parseDateIE8(str) {
// '2012-11-10' -> '2012/11/10' (IE8 支援斜線格式)
return new Date(Date.parse(str.replace(/-/g, '/')));
}
2023-11-10T00:00:00Z)或 Unix Timestamp(毫秒數),前端統一 new Date(timestamp) 最穩健。es5-shim + es6-shim 並封裝統一日期工具模組。