21 lines
667 B
TypeScript
21 lines
667 B
TypeScript
|
|
import dayjs from 'dayjs';
|
||
|
|
|
||
|
|
/** 相对时间展示:刚刚 / N 分钟前 / N 小时前 / N 天前,超过 7 天回退完整日期 */
|
||
|
|
export function formatRelativeTime(value: string | number) {
|
||
|
|
const time = dayjs(value);
|
||
|
|
if (!time.isValid()) return '';
|
||
|
|
|
||
|
|
const now = dayjs();
|
||
|
|
const diffMinutes = now.diff(time, 'minute');
|
||
|
|
if (diffMinutes < 1) return '刚刚';
|
||
|
|
if (diffMinutes < 60) return `${diffMinutes} 分钟前`;
|
||
|
|
|
||
|
|
const diffHours = now.diff(time, 'hour');
|
||
|
|
if (diffHours < 24) return `${diffHours} 小时前`;
|
||
|
|
|
||
|
|
const diffDays = now.diff(time, 'day');
|
||
|
|
if (diffDays < 7) return `${diffDays} 天前`;
|
||
|
|
|
||
|
|
return time.format('YYYY-MM-DD HH:mm');
|
||
|
|
}
|