function getDays(startStr, endStr) {
// 兼容 '2024-01-01' / '2024/01/01'
const start = new Date(startStr.replace(/-/g, '/'));
const end = new Date(endStr.replace(/-/g, '/'));
if (isNaN(start) || isNaN(end)) return NaN;
const diffMs = Math.abs(end - start);
return diffMs / 1000 / 60 / 60 / 24; // 毫秒 → 天
}
<input type="date" id="startDate" onchange="calc()">
<input type="date" id="endDate" onchange="calc()">
<span id="result">0</span> 天
<script>
function calc() {
const s = document.getElementById('startDate').value;
const e = document.getElementById('endDate').value;
if (s && e) {
const days = getDays(s, e);
document.getElementById('result').textContent = Number.isInteger(days) ? days : days.toFixed(1);
}
}
</script>
YYYY-MM-DD,無需日曆插件。new Date('2024-01-01') 解析為 UTC 導致跨天誤差。// Day.js (2KB)
const days = dayjs(endDate).diff(dayjs(startDate), 'day');
原生 API 已足夠輕量,推薦優先使用 type="date" + 原生 Date 計算,無額外依賴。