首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

JS 日期差值計算:文本框選擇日期自動換算天數

     編輯:程式設計疑難解答

核心函數

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>

關鍵點提示

  • type="date":原生日期選擇器,返回格式固定 YYYY-MM-DD,無需日曆插件。
  • replace(/-/g, '/'):修復 Safari/iOS 下 new Date('2024-01-01') 解析為 UTC 導致跨天誤差。
  • Math.abs:不限制起止順序,自動取絕對天數。
  • 業務邏輯:若需「含首尾天數 +1」或「僅工作日」,需額外業務計算,不可濫用通用差值函數。

進階:Moment.js / Day.js 版

// Day.js (2KB)
const days = dayjs(endDate).diff(dayjs(startDate), 'day');

原生 API 已足夠輕量,推薦優先使用 type="date" + 原生 Date 計算,無額外依賴。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved