实现倒计时/正计时功能 moment
现在已知一个毫秒时间,根据这个时间进行倒计时/正计时,借用moment插件,我们平常进行时间转换的时候,是为了获得当前时刻,比如以下的例子:
let a= new Date()
console.log("a",a)
console.log("b",moment(a).format('YYYY-MM-DD HH:mm:ss'))
//输出结果:
//a Thu Nov 25 2021 16:50:50 GMT+0800 (中国标准时间)
//b, "2021-11-25 16:50:50"
但是我们要根据毫秒(1000ms)进行时间转换,继续用上述的方法
let aa=10000
console.log('aa',moment(aa).format('YYYY-MM-DD HH:mm:ss'))
//输出结果:
//aa 1970-01-01 08:00:10
发现时刻为8点,不是我们想要的结果,因为我们只是想根据10000ms计算出时长进行倒计时,但是使用moment()转换成的是北京时间,我们想要的是utc时间
那么问题来了,utc时间和北京时间有什么区别,时间戳是指从1970年1月1日 00:00:00,到现在的毫秒数
时间戳为0(ms)的时间对应
utc时间 1970年1月1日 00:00:00
北京时间 1970年1月1日 08:00:00
所以通过毫秒转换成utc时间 才是我们想要的结果,正好moment支持utc时间转换
let aa=10000
console.log('aa',moment.utc(aa).format('YYYY-MM-DD HH:mm:ss'))
//输出结果:
//aa 1970-01-01 00:00:10
这样的话,转换成utc时间,就可以取时分秒进行倒计时了
接下来,倒计时怎么实现,更多功能查看moment
let aa=moment.utc(10000)
aa=aa.add(1, 's');//加一秒00:00:11
aa=aa.subtract(1,'s')//减一秒00:00:10
console.log(aa.format('HH:mm:ss'))//00:00:10
完整代码:根据时间和类型进行倒计时或者正计时
const [handleTime, setHandleTime] = useState<any>('');
const [overTime, setOverTime] = useState(false);
const handleTimerID: any = useRef();
const caculateTime = (time = 0, type = 'subtract') => {
clearInterval(handleTimerID.current);
setHandleTime(moment.utc(time).format('HH:mm:ss'));
let tempTime: any;
tempTime = moment.utc(time);
handleTimerID.current = setInterval(() => {
if (tempTime.valueOf() === 0) {
type = 'add';
setOverTime(true);
}
tempTime = tempTime[type](1, 's');
setHandleTime(tempTime.format('HH:mm:ss'));
}, 1000);
};
实现效果: