JavaScript - Date.now()返回错误的日期

时间:2018-04-08 10:49:29

标签: javascript date

我希望获得设定日期和今天之间的天数。

我无法弄清楚为什么当我今天动态约会而不是硬编码时,我会一直收到错误的结果。

HTML

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

JS

var startDate = new Date(2016,04,01).getTime();
var todayDate1 = new Date().getTime();
var todayDate2 = Date.now();
var hardcodedDate = new Date(2018,04,08).getTime();

$("#today1").html(Math.floor((todayDate1 - startDate)/8.64e7));
$("#today2").html(Math.floor((todayDate2 - startDate)/8.64e7));
$("#hardcoded").html(Math.floor((hardcodedDate - startDate)/8.64e7));

结果

707 days - wrong
707 days - wrong
737 days - correct

JSFiddle

我错过了什么?

1 个答案:

答案 0 :(得分:3)

今天是2018年4月8日。new Date(2018, 4, 8) 5月 2018年8月。引用MDN documentation on the Date constructor

  

参数月份为0-based。这意味着January = 0December = 11

使用3作为月份参数来引用四月。

相关问题