首先获得两个时间的时间戳
var newdate = new Date('2021-01-22 21:25:00').getTime();
var olddate = new Date().getTime();
然后相减获得相差时间的毫秒数
var difference = newdate - olddate
计算还有多少天,多少小时,多少分,多少秒
1 var day = parseInt(difference / 1000 / 60 / 60 / 24);
2 difference = difference % (1000 * 60 * 60 * 24)
3 var hours = parseInt(difference / 1000 / 60 / 60);
4 difference = difference % (1000 * 60 * 60)
5 var m = parseInt(difference / 1000 / 60);
6 difference = difference % (1000 * 60)
7 var s = parseInt(difference / 1000)
最后打印一下,就是距离目标时间的天数(精确到秒)
console.log(day + '-' + hours + '-' + m + '-' + s);
怎么让他显示在页面上并且一直动呢,,这时候我们的定时器就登场了
首先创建一个div盒子存放所有的数字
<div id="show"><span></span>天<span></span>小时<span></span>分<span></span>秒</div>
然后动态添加
show\[0\].innerHTML = day;
show\[1\].innerHTML = hours;
show\[2\].innerHTML = m;
show\[3\].innerHTML = s;
封装函数,并加入定时器,
完整代码来啦(直接复制粘贴到html就可以运行)