import dayjs from 'dayjs'; import duration from 'dayjs/plugin/duration'; import relativeTime from 'dayjs/plugin/relativeTime'; dayjs.extend(duration); dayjs.extend(relativeTime); /** * Relative时间的格式化函数 * @param value */ export function getRelativeTime(value: number) { const pad0 = (v: number) => String(v).padStart(2, '0'); const duration = dayjs.duration(value); const hours = Math.floor(duration.asHours()); const mins = Math.floor(duration.asMinutes()) - hours * 60; const sec = Math.floor(duration.asSeconds()) - mins * 60 - hours * 60 * 60; if (hours) { return `${pad0(hours)}:${pad0(mins)}:${pad0(sec)}`; } else if (mins) { return `00:${pad0(mins)}:${pad0(sec)}`; } else if (sec) { return `00:00:${pad0(sec)}`; } else { return '00:00:00'; } } /** * Absolute时间的格式化函数 * @param time */ export function getAbsoluteTime(time: number) { const Format = (data: Date, fmt: string) => { interface INameToValueMap { [key: string]: any; } const o: INameToValueMap = { 'M+': data.getMonth() + 1, 'd+': data.getDate(), 'h+': data.getHours(), 'm+': data.getMinutes(), 's+': data.getSeconds(), 'q+': Math.floor((data.getMonth() + 3) / 3), S: data.getMilliseconds(), }; if (/(y+)/.test(fmt)) { fmt = fmt.replace( RegExp.$1, (data.getFullYear() + '').substr(4 - RegExp.$1.length), ); } for (const k in o) { if (new RegExp('(' + k + ')').test(fmt)) { fmt = fmt.replace( RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length), ); } } return fmt; }; const t = new Date(time); return Format(t, 'yyyy-MM-dd hh:mm:ss'); }