javascript - 日期差异大于预期

标签 javascript datetime

我正在学习在 Javascript 中使用 Date 对象。尝试计算现在与某个设定日期之间的差异,但它返回的值比预期的值大得多。代码笔是 here ,我似乎无法弄清楚我做错了什么......帮助?

var setdate = new Date(2014, 4, 27, 14,30); //27th of April this year at 14:30
var now = new Date(); //Now, whenever this code runs
var diff = Math.round((setdate.getTime() - now.getTime())/1000); //Difference in seconds

function NiceTimer(delta) { //Decompose the difference in seconds into date units.

  this.days = Math.floor(delta/ 86400);
  delta -= this.days*86400; //Subtract the value once it has been "extracted".

  this.hours = Math.floor(delta/ 3600);
  delta -= this.hours*3600;

  this.minutes = Math.floor(delta/ 60);
  delta -= this.minutes*60;

  this.seconds = delta;

  this.printString = function() {
    return "The event starts in "+this.days+" days, "+this.hours+" hours, "+this.minutes+" minutes and "+this.seconds+" seconds"; //Output a readable countdown string
  }
}

var timer = new NiceTimer(diff);

var el = document.getElementById("timer");
el.innerHTML = timer.printString();

最佳答案

var setdate = new Date(2014, 4, 27, 14,30); //27th of April this year at 14:30

将四更改为三,月份从索引零开始。

var setdate = new Date(2014, 3, 27, 14,30);

Date @ MDN :

month Integer value representing the month, beginning with 0 for January to 11 for December.

关于javascript - 日期差异大于预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22934154/

相关文章:

javascript - 找出代码中哪一部分导致了 JS 中垃圾回收的最多

javascript - 如何正确地从每一侧(上、左、下、右)创建 2d 对象碰撞

javascript - d3 时间格式返回 null

php - 将字符串日期转换为 MySQL 日期时间

javascript - unserscore,使用 "{{","}}"作为插值符号,我遇到了异常

javascript - Angular2 JQuery,如何制作document.ready函数

Python:检查解析的日期时间是否具有正确的时区

python - 使用to_datetime转换列时遇到问题,语法有什么问题?

python - PyQt5 和 datetime.datetime.strptime 之间的冲突

javascript - 有条件地进入 NavLink