You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中Date.now()返回错误日期,动态计算日期天数差异常

动态获取今日日期计算天数差出错的原因与解决办法

我一眼就看出问题所在啦!你遇到的问题根本不是动态获取今日日期的方法有问题,而是JavaScript Date对象的月份参数是从0开始计数的,这是个超级容易踩的坑!

先看你给出的代码片段:

<span id="today1">xxx</span> days - wrong <br>
<span id="today2">xxx</span> days - wrong <br>
<span id="hardcoded">xxx</span> days - correct
var startDate = new Date(2016,04,01).getTime();
var todayDate1 = new Date().getTime();
var todayDate2 = Date.now();
var hardcoded = // 你这里应该是写了正确的月份参数,所以结果正常

问题根源

你写的new Date(2016,04,01),这里的04对应的不是4月,而是5月!因为JavaScript里月份的取值范围是0(1月)~11(12月),所以你实际设置的起始日期是2016年5月1日,而不是你预期的2016年4月1日。这就导致用动态今日日期计算差值时,结果和你预期的不一样,但硬编码日期的时候,你可能无意中用了正确的月份参数(比如用03代表4月),所以结果是对的。

解决办法

把起始日期的月份参数改成03(对应4月)就可以了,动态获取今日日期的方法new Date().getTime()和Date.now()都是完全正确的,不需要修改。

这里给你一个完整的可运行代码示例:

<span id="today1">xxx</span> days - now correct <br>
<span id="today2">xxx</span> days - now correct <br>
<span id="hardcoded">xxx</span> days - correct

<script>
// 修正月份参数:03代表4月
var startDate = new Date(2016, 03, 01).getTime();
var todayDate1 = new Date().getTime();
var todayDate2 = Date.now();
// 模拟你正确的硬编码日期逻辑
var hardcodedDate = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()).getTime();

// 计算天数差:时间戳相减后除以一天的毫秒数(24*60*60*1000=86400000)
function calculateDaysDiff(timestamp1, timestamp2) {
  return Math.floor(Math.abs(timestamp1 - timestamp2) / 86400000);
}

// 更新页面显示
document.getElementById('today1').textContent = calculateDaysDiff(startDate, todayDate1);
document.getElementById('today2').textContent = calculateDaysDiff(startDate, todayDate2);
document.getElementById('hardcoded').textContent = calculateDaysDiff(startDate, hardcodedDate);
</script>

额外提示

以后创建Date对象时,一定要记住月份是0起始的。如果怕记错,也可以用字符串形式传入日期,比如new Date('2016-04-01'),这种方式月份是正常的1-12,不容易出错(不过要注意时区问题,字符串形式默认是UTC时区,可能需要根据需求调整)。

内容的提问来源于stack exchange,提问作者pika_pika

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:56:00