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方法计算两个时间段的差值,并以想要的形式返回,默认以毫秒差形式返回html
//定义一个当即执行的函数 (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(); })();
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> ) }