moment计算两个工夫差值
moment(endTime).diff(moment(startTime), 'years')
moment(endTime).diff(moment(startTime), 'months')
moment(endTime).diff(moment(startTime), 'days') // 开始工夫和完结工夫的时间差,以“天”为单位;endTime和startTime都是毫秒数
moment(endTime).diff(moment(startTime),'minutes' )
moment(endTime).diff(moment(startTime), 'seconds')
原生实现
用立刻执行函数封装一个倒计时插件,外头用moment插件中的diff办法计算两个时间段的差值,并以想要的模式返回,默认以毫秒差模式返回
//定义一个立刻执行的函数
(function () {
var Ticts=function Ticts() {
this.ticts = {};
};
Ticts.prototype.createTicts=function(id, dealline) {
var ticts=this;
var time=moment(dealline).diff(moment());
var _ticts=this.ticts[id] = {
dealine: dealline
, id: id
, time: time
, interval: setInterval(function () {
var t = null;
var d = null;
var h = null;
var m = null;
var s = null;
//js默认工夫戳为毫秒,须要转化成秒
t = _ticts.time / 1000;
d = Math.floor(t / (24 * 3600));
h = Math.floor((t - 24 * 3600 * d) / 3600);
m = Math.floor((t - 24 * 3600 * d - h * 3600) / 60);
s = Math.floor((t - 24 * 3600 * d - h * 3600 - m * 60));
//这里能够做一个格式化的解决,甚至做毫秒级的页面渲染,基于DOM操作,太多个倒计时一起会导致页面性能降落
document.getElementById(id).innerHTML = d + '天' + h + '小时' + m + '分钟' + s + '秒';
_ticts.time -= 1000;
if (_ticts.time < 0)
ticts.deleteTicts(id);//判断是否到期,到期后主动删除定时器
}, 1000)
}
};
Ticts.prototype.deleteTicts = function(id) {
clearInterval(this.ticts[id].interval);//分明定时器的办法,须要定时器的指针作为参数传入clearInterval
delete this.ticts[id];//通过delete的办法删除对象中的属性
};
//新建一个ticts对象,放到window全局函数中,那么在html页面是(或者其余js文件)能够拜访该对象
window.Ticts=new Ticts();
})();
React实现
import React from 'react';
import moment from 'moment';
interface props {
deadline: number; // 截止工夫戳
}
const CountDown = (props: IProps) => {
const { deadline } = props;
const [time, setTime] = useState(Date.now());
useEffect(() => {
let timer: NodeJS.Timeout | null = null;
if (deadline && deadline > time) {
timer = setInterval(() => {
if (deadline - time < 1000 && timer) {
if (timer) clearInterval(timer);
}
setTime(Date.now());
}, 1000);
}
return () => {
if (timer) clearInterval(timer);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [deadline]);
const format = () => {
const t = moment(deadline).diff(moment(time), 'seconds');
const d = Math.floor(t / (24 * 3600));
const h = Math.floor((t - 24 * 3600 * d) / 3600);
const m = Math.floor((t - 24 * 3600 * d - h * 3600) / 60);
const s = Math.floor(t - 24 * 3600 * d - h * 3600 - m * 60);
return [d * 24 + h, m, s];
};
const countDown = format();
return (
<span>还剩{countDown[0]}小时{countDown[1]}分钟{countDown[2]}秒</span>
)
}
发表回复