关于倒计时的实现:
首先是按照自己的逻辑实现的代码:
<style>
div {
width: 100%;
margin: 0 auto;
}
p {
text-align: center;
font-size: 40px;
}
</style>
<body>
<div>
<p id="text"></p>
</div>
<script>
//定时器放在最外层
setInterval(function () {
var fTime = new Date(2023, 3, 28, 17, 0, 0); // 输入要计算的时间
var nTime = new Date(); // 当前计算机时间
function getDiff(fTime, nTime) {
let futureTime = fTime.getTime(); //获取两时间节点时间戳
let nowTime = nTime.getTime();
//计算得到相差秒数,并将毫秒转化为秒
let remainingTime = Math.ceil((futureTime - nowTime) / 1000);
//开始换算时间戳
let day = Math.floor(remainingTime / (24 * 60 * 60));
let hours = Math.floor((remainingTime % (24 * 60 * 60)) / (60 * 60));
let minutes = Math.floor((remainingTime % (60 * 60)) / 60);
let seconds = remainingTime % 60;
return { day: day, hours: hours, minutes: minutes, seconds: seconds };
}
let {
day: day,
hours: hours,
minutes: minutes,
seconds: seconds,
} = getDiff(fTime, nTime);
let text1 = document.getElementById("text");
text1.innerText = `距离五一还有${day}天${hours}小时${minutes}分${seconds}秒`;
}, 1000);
</script>
下面是请教朋友的代码
<script>
const laborDayTime = new Date("5 1,2023").getTime();
setInterval(function () {
let nowDayTime = new Date().getTime();
let remainingTime = getRemainingTime(laborDayTime - nowDayTime);
console.log(`距离距离五一还有:${remainingTime}`);
}, 1000);
function getRemainingTime(time) {
let day = getDateTimeDay(time);
let hours = getDateTimeHour(time);
let minutes = getDateTimeMinute(time);
let seconds = getDateTimeSecond(time);
return `${day}天${hours}小时${minutes}分${seconds}秒`;
}
function getDateTimeSecond(time) {
return Math.floor(time / 1000) % 60;
}
function getDateTimeMinute(time) {
return Math.floor((time / (60 * 1000)) % 60);
}
function getDateTimeHour(time) {
return Math.floor((time / (60 * 60 * 1000)) % 24);
}
function getDateTimeDay(time) {
return Math.floor(time / (24 * 60 * 60 * 1000));
}
</script>
最后了解了moment.js的某些运用
标签:60,实现,倒计时,seconds,let,time,day,Math From: https://www.cnblogs.com/zerotwo-zrx/p/17352326.html