参考链接
https://blog.csdn.net/chatgpt002/article/details/134396933
方式一
function countdown(endTime) {
const countDownElement = document.getElementById('countdown');
const timer = setInterval(function () {
const now = new Date().getTime();
const distance = endTime - now;
if (distance < 0) {
clearInterval(timer);
countDownElement.innerHTML = "倒计时结束";
return;
}
const days = Math.floor(distance / (1000 * 60 * 60 * 24));
const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((distance % (1000 * 60)) / 1000);
countDownElement.innerHTML = days + "天 " + hours + "小时 "
+ minutes + "分钟 " + seconds + "秒 ";
}, 1000);
}
// 使用方法:在HTML中有一个id为"countdown"的元素
// 设置结束时间,格式为yyyy-mm-dd hh:mm:ss
countdown(new Date('2024-12-31 23:59:59').getTime());
方式二
//倒计时效果
function countDown(time){
const countDownElement = document.getElementById('countdown');
const timer = setInterval(function () {
var nowTime=+new Date();//返回当前时间总的毫秒数
var inputTime=+new Date(time);//返回用户输入时间总毫秒数
var times=(inputTime-nowTime)/1000;//剩余时间总的秒数
if (times < 0) {
clearInterval(timer);
countDownElement.innerHTML = "倒计时结束";
return;
}
//转换时分秒
var d=parseInt(times/60/60/24);
var h=parseInt(times/60/60%24);
var m=parseInt(times/60%60);
var s=parseInt(times%60);
// return d+'天'+h+'时'+m+'分'+s+'秒';
countDownElement.innerHTML = d + "天 " + h + "小时 "
+ m + "分钟 " + s + "秒 ";
}, 1000);
}
countDown('2024-8-31 20:30:00');