我正在制作一个倒数计时器,以计数特殊事件。代码可以正常运行,但是一天之内就算错了。我认为该代码不会从日期起采用h值,但我不知道如何使其生效。我认为几个小时就错了。我的当地时间是UTC+01:00
。
var eventDay = new Date("Feb 30, 2019 10:00:00").getTime();
var distance = setInterval(function(){
var now = new Date().getTime();
var distance = eventDay - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60 * 24));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var sec = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("days").innerHTML = days;
document.getElementById("hours").innerHTML = hours;
document.getElementById("minutes").innerHTML = minutes;
document.getElementById("sec").innerHTML = sec;
}, 1000);
答案 0 :(得分:1)
要获得预期结果,请使用以下选项
对于正确的小时数,应该使用(1000 * 60 * 60),而不是(1000 * 60 * 60 * 24),因为小时数计算错误(当前计算的小时数是与天计算)
为缺少的日期添加+1,因为计算不包括开始日期和结束日期
var eventDay = new Date("Feb 28, 2019 10:00:00").getTime();
var distance = setInterval(function(){
var now = new Date().getTime();
var distance = eventDay - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24)) + 1;
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var sec = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("days").innerHTML = days;
document.getElementById("hours").innerHTML = hours;
document.getElementById("minutes").innerHTML = minutes;
document.getElementById("sec").innerHTML = sec;
}, 1000);
<span id="days"></span>d
<span id="hours"></span>h
<span id="minutes"></span>m
<span id="sec"></span>s
答案 1 :(得分:0)
您遇到的问题是此行
var godziny = Math.floor((pozostalyCzas % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60 * 24));
您应该将其更改为此
var godziny = Math.floor((pozostalyCzas % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));