我正在学习在Javascript中使用Date对象。试图计算现在和某个设定日期之间的差异,但它返回的值比想要的大得多。 codepen是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();
答案 0 :(得分:5)
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);
<强>月强> 表示月份的整数值,从1月的0开始到12月的11。