← 返回完整题库
JavaScript简单

实现一个函数, 计算两个日期之间的天数差

参考答案

function diffDays(a, b) {
  const d1 = new Date(a), d2 = new Date(b);
  const t1 = Date.UTC(d1.getFullYear(), d1.getMonth(), d1.getDate());
  const t2 = Date.UTC(d2.getFullYear(), d2.getMonth(), d2.getDate());
  return Math.round(Math.abs(t2 - t1) / 86400000);
}

要点:

  • 用 UTC 或先抹掉时分秒,避免夏令时/时区导致 23/25 小时误差;
  • 需要"含首尾"时 +1;
  • 跨月跨年由 Date 自动处理。

本题来自 计算机知识面试题库,共 921 道题。