JavaScript Date 物件相減回傳**毫秒數差值**。換算天數公式:
天數 = Math.abs(date1 - date2) / (1000 * 60 * 60 * 24)
/**
* 計算兩日期相差天數(含起迄日)
* @param {string|Date|HTMLInputElement} start - 開始日期
* @param {string|Date|HTMLInputElement} end - 結束日期
* @returns {number} 相差天數(含首尾日),無效輸入回傳 NaN
*/
function getDayDiff(start, end) {
const d1 = normalizeDate(start);
const d2 = normalizeDate(end);
if (isNaN(d1) || isNaN(d2)) return NaN;
// 歸零時間部分,避免時區/夏令時間導致跨日誤差
d1.setHours(0, 0, 0, 0);
d2.setHours(0, 0, 0, 0);
const diffMs = Math.abs(d1 - d2);
return Math.round(diffMs / 86400000) + 1; // +1 含首尾日
}
/** 將各種輸入正規化為 Date 物件 */
function normalizeDate(input) {
if (input instanceof Date) return new Date(input.getTime()); // 複製避免副作用
if (input instanceof HTMLInputElement) input = input.value;
if (typeof input !== 'string') return NaN;
// 支援 YYYY-MM-DD、YYYY/MM/DD、ISO 8601
const parts = input.split(/[-/]/);
if (parts.length !== 3) return NaN;
const [y, m, d] = parts.map(Number);
if (![y, m, d].every(Number.isFinite)) return NaN;
// month 為 0-based
return new Date(y, m - 1, d);
}
// 使用範例
const startEl = document.getElementById('startDate');
const endEl = document.getElementById('endDate');
const resultEl = document.getElementById('result');
function calc() {
const days = getDayDiff(startEl, endEl);
resultEl.textContent = isNaN(days) ? '請輸入有效日期 (YYYY-MM-DD)' : `相差 ${days} 天`;
}
startEl.addEventListener('change', calc);
endEl.addEventListener('change', calc);
<label>開始日期:<input type="date" id="startDate"></label>
<label>結束日期:<input type="date" id="endDate"></label>
<button type="button" onclick="calc()">計算</button>
<div id="result"></div>
setHours(0,0,0,0) 消除時區與夏令時間導致的「同一天卻差 1 小時」誤差。<input type="date"> 元素直接傳入、ISO 字串、斜線分隔格式。Temporal 提案 (Stage 3)// 未來標準 API(目前需 Polyfill)
import { Temporal } from '@js-temporal/polyfill';
const days = Temporal.PlainDate.from('2024-01-01').until(Temporal.PlainDate.from('2024-01-10')).days; // 9
| 錯誤寫法 | 問題 | 正確寫法 |
|---|---|---|
new Date('2024-01-01') | Safari/舊瀏覽器不支援連字號格式 | new Date('2024/01/01') 或 new Date(2024,0,1) |
| 直接相減不歸零時間 | 跨 DST 邊界誤差 ±1 天 | setHours(0,0,0,0) |
用 getDate() 相減 | 忽略月份/年份差異 | 完整 Date 物件相減 |
這個函式庫級工具函式可直接複製到專案中,解決 99% 的日期天數計算需求。