实现元旦倒计时函数,输出格式为'现在距离元旦还有xx天xx小时xx分xx秒'
function restTime() {
const EndTime = new Date("2020/01/01 00:00:00");
const NowTime = new Date();
const t = EndTime.getTime() - NowTime.getTime();
const d = Math.floor(t / 1000 / 60 / 60 / 24);
const h = Math.floor(t / 1000 / 60 / 60 % 24);
const m = Math.floor(t / 1000 / 60 % 60);
const s = Math.floor(t / 1000 % 60);
console.log(`现在距离元旦还有${d}天${h}小时${m}分${s}秒`);
}
setInterval(restTime, 1000);
但是,这样直接把时间和节日名都写死了,假如要换为春节就需要修改函数内部,所以抽离参数
function restTime(str,name) {
return ()=>{
const EndTime = new Date(str);
const NowTime = new Date();
const t = EndTime.getTime() - NowTime.getTime();
const d = Math.floor(t / 1000 / 60 / 60 / 24);
const h = Math.floor(t / 1000 / 60 / 60 % 24);
const m = Math.floor(t / 1000 / 60 % 60);
const s = Math.floor(t / 1000 % 60);
console.log(`现在距离${name}还有${d}天${h}小时${m}分${s}秒`);
}
}
setInterval(restTime("2020/01/01 00:00:00",'元旦'), 1000);
-
效果:
网友评论