跳到主要内容

倒计时功能

1 分钟阅读

开始

原生写法:

const laborDayTime = new Date("5 1,2023").getTime();
setInterval(() => {
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));
}

使用moment.js写法:

var moment = require('./js/moment.js');
const laborDayTime =moment("2023-05-01 00:00:00.000")
setInterval(function () {
let remainingTime = moment.duration(laborDayTime.diff(moment()))
console.log(`距离距离五一还有:${remainingTime._data.days}${remainingTime._data.hours}小时${remainingTime._data.minutes}${remainingTime._data.seconds}`);
}, 1000);
评论
0条评论

添加新评论

昵称
邮箱
网址