// 日期格式化工具 export const dateUtils = { // 格式化日期 formatDate: (date: Date | string, format = 'YYYY-MM-DD'): string => { const d = new Date(date); if (isNaN(d.getTime())) { return ''; } const year = d.getFullYear(); const month = String(d.getMonth() + 1).padStart(2, '0'); const day = String(d.getDate()).padStart(2, '0'); const hours = String(d.getHours()).padStart(2, '0'); const minutes = String(d.getMinutes()).padStart(2, '0'); const seconds = String(d.getSeconds()).padStart(2, '0'); return format .replace('YYYY', String(year)) .replace('MM', month) .replace('DD', day) .replace('HH', hours) .replace('mm', minutes) .replace('ss', seconds); }, // 获取相对时间(如:2小时前) getRelativeTime: (date: Date | string): string => { const now = new Date(); const target = new Date(date); const diffMs = now.getTime() - target.getTime(); // 如果目标时间在未来,返回绝对时间 if (diffMs < 0) { return dateUtils.formatDate(target, 'YYYY-MM-DD HH:mm'); } const diffSeconds = Math.floor(diffMs / 1000); const diffMinutes = Math.floor(diffSeconds / 60); const diffHours = Math.floor(diffMinutes / 60); const diffDays = Math.floor(diffHours / 24); const diffWeeks = Math.floor(diffDays / 7); const diffMonths = Math.floor(diffDays / 30); const diffYears = Math.floor(diffDays / 365); if (diffSeconds < 60) { return '刚刚'; } else if (diffMinutes < 60) { return `${diffMinutes}分钟前`; } else if (diffHours < 24) { return `${diffHours}小时前`; } else if (diffDays < 7) { return `${diffDays}天前`; } else if (diffWeeks < 4) { return `${diffWeeks}周前`; } else if (diffMonths < 12) { return `${diffMonths}个月前`; } else { return `${diffYears}年前`; } }, // 检查是否是今天 isToday: (date: Date | string): boolean => { const today = new Date(); const target = new Date(date); return today.getFullYear() === target.getFullYear() && today.getMonth() === target.getMonth() && today.getDate() === target.getDate(); }, // 检查是否是昨天 isYesterday: (date: Date | string): boolean => { const yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1); const target = new Date(date); return yesterday.getFullYear() === target.getFullYear() && yesterday.getMonth() === target.getMonth() && yesterday.getDate() === target.getDate(); } };