JavaScript 倒计时
const moment = require("moment");
const fromNow = (time, format = 'HH:mm:ss') => {
// 格式化时间
const _format = (value = {}) => format
.replace('HH', value.HH || '00')
.replace('mm', value.mm || '00')
.replace('ss', value.ss || '00')
.replace('H', value.H || '0')
.replace('m', value.m || '0')
.replace('s', value.s || '0');
// 判断输入参数是否为空
if (!time) {
return _format();
}
// 获取两个时间的时差
// moment().diff() 返回两个时间相差的秒数
const diff = moment(time).diff(moment());
// 如果是负数,则表示时间已到
if (diff <= 0) {
return _format();
}
// 1小时等于=1000*60*60 秒,以此类推
const hoursScale = 1000 * 60 * 60;
const minutesScale = 1000 * 60;
const secondsScale = 1000;
// 相除取整,小数部分为下个时间单位的总数
// 小时 = 总秒数 / hoursScale
// 分钟 = (总秒数 - 小时占用秒数) / minutesScale
const hours = parseInt(diff / hoursScale);
const minutes = parseInt((diff - hours * hoursScale) / minutesScale);
const seconds = parseInt(
(diff - hours * hoursScale - minutes * minutesScale) / secondsScale
);
// 如果时间个位数,则补0
const patchHours = hours < 10 ? '0' + hours : hours;
const patchMinutes = minutes < 10 ? '0' + minutes : minutes;
const patchSeconds = seconds < 10 ? '0' + seconds : seconds;
return _format({
HH: patchHours,
mm: patchMinutes,
ss: patchSeconds,
H: hours,
m: minutes,
s: seconds
});
}