相差天数
--
--
新日期
--
--

日期差计算的原理与公式

两个日期之间的天数差,本质上就是两个日期时间戳的差值除以一天的毫秒数。在 JavaScript 中,一天等于 1000 × 60 × 60 × 24 = 86,400,000 毫秒。

日期差公式 天数差 = Math.round((结束日期.getTime() - 开始日期.getTime()) / 86400000)

示例:开始日期 2026-05-01,结束日期 2026-05-10,时间戳差值为 9 天 × 86400000 毫秒,相除后得到 9 天。如果开始日期在结束日期之后,结果为负数。

日期加减的原理

给定一个日期,加上或减去 N 天,实际上就是改变日期的日部分。JavaScript 的 Date 对象提供了 setDate() 方法,会自动处理月份和年份的变化(包括闰年)。

日期加减算法 let date = new Date('2026-05-01');
date.setDate(date.getDate() + 30);
// date 变成 2026-05-31

常见应用场景

  • 项目管理: 计算工期,或从开始日期加上工作天数推出截止日期。
  • 孕期计算: 从末次月经第一天加 280 天即为预产期。
  • 合同倒计时: 计算距离合同到期还有多少天。
  • 纪念日提醒: 计算恋爱纪念日、结婚纪念日距离今天还有多久。

常见问题

计算结果包含开始和结束当天吗?

本工具计算的是两个日期间的绝对差值。例如,从 5 月 1 日到 5 月 2 日相差 1 天。如果需要包含首尾两天,请在结果上加 1。

会不会因为闰年或时区出错?

不会。JavaScript 的 Date 对象内建了对闰年和时区的支持,日期相减得到的是 UTC 午夜之间的差值,所以结果完全准确。

加减天数时遇到月底会自动进位吗?

是的。例如给 5 月 31 日加 1 天,结果会自动变为 6 月 1 日。JavaScript 的 setDate() 方法会自动处理月份和年份的进位。

Day Difference
--
--
New Date
--
--

How Date Differences Are Calculated

The difference in days between two dates is simply the difference in milliseconds divided by the number of milliseconds in a day (86,400,000).

Formula Day Difference = Math.round((End Date - Start Date) / 86400000)

Example: May 1 to May 10, 2026 = 9 days.

Adding or Subtracting Days

JavaScript's setDate() method handles month and year overflow automatically.

FAQ

Does it include both start and end dates?

No, the result is the exact number of days between the two dates. If you need an inclusive count, add 1 to the result.

Is leap year supported?

Yes, JavaScript's Date engine correctly handles all leap years.

Will adding days automatically roll over months?

Yes. Adding 1 day to May 31 results in June 1. The setDate() method handles month and year rollovers seamlessly.