
//取倒计时(天时分秒)
function getTimeLeft(datetimeTo) {
// console.log(000000000)
// console.log(datetimeTo)
// 计算目标与现在时间差(毫秒)
let time1 = new Date(datetimeTo).getTime();
let time2 = new Date().getTime();
let mss = time1 - time2;
let array = [];
// 将时间差(毫秒)格式为:天时分秒
let days = parseInt(mss / (1000 * 60 * 60 * 24));
let hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
let seconds = parseInt((mss % (1000 * 60)) / 1000);
array = [days, hours, minutes, seconds]
//return days + "天" + hours + "时" + minutes + "分" + seconds + "秒"
// return `${days}<text>天</text>${hours}<text>时</text>${minutes}<text>分</text>${seconds}<text>秒</text>`
return array
}
module.exports = {
getTimeLeft: getTimeLeft
}
使用的页面调用
const util = require('../../utils/util.js');
Page({
data:{
timeLeft:[]
},
onload:function(){
this.data.timer = setInterval(() => { //注意箭头函数!!
this.setData({
timeLeft: util.getTimeLeft(date)//使用了util.getTimeLeft,这里传的date是时间
});
if (this.data.timeLeft == [0, 0, 0, 0]) {//"0天0时0分0秒"
clearInterval(this.data.timer);
}
}, 1000);
}
})
本文介绍了一种在前端应用中实现倒计时功能的方法,通过JavaScript计算目标日期与当前时间的差值,并将其转换为天、时、分、秒的格式进行显示。此功能适用于各类需要展示时间倒数的应用场景。
1347

被折叠的 条评论
为什么被折叠?



