/** * Center 模块格式化工具函数 * * 这些是纯函数,提取到组件外部避免每次渲染重建 */ /** * 格式化相对时间(如 "5分钟前"、"3天前") * @param dateString 日期字符串 * @returns 格式化后的相对时间字符串 */ export function formatRelativeTime(dateString: string | null | undefined): string { if (!dateString) return ''; const date = new Date(dateString); const now = new Date(); const diffTime = Math.abs(now.getTime() - date.getTime()); const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); if (diffDays < 1) { const diffHours = Math.ceil(diffTime / (1000 * 60 * 60)); if (diffHours < 1) { const diffMinutes = Math.ceil(diffTime / (1000 * 60)); return `${diffMinutes}分钟前`; } return `${diffHours}小时前`; } else if (diffDays < 7) { return `${diffDays}天前`; } else { return date.toLocaleDateString('zh-CN'); } } /** * 格式化数字(如 10000 → "1w",1500 → "1.5k") * @param num 数字 * @returns 格式化后的字符串 */ export function formatCompactNumber(num: number | null | undefined): string { if (!num) return '0'; if (num >= 10000) { return (num / 10000).toFixed(1) + 'w'; } else if (num >= 1000) { return (num / 1000).toFixed(1) + 'k'; } return num.toString(); } /** * 根据热度分数获取颜色 * @param score 热度分数 (0-100) * @returns Chakra UI 颜色名称 */ export function getHeatColor(score: number): string { if (score >= 80) return 'red'; if (score >= 60) return 'orange'; if (score >= 40) return 'yellow'; return 'green'; } /** * 根据涨跌幅获取颜色 * @param changePercent 涨跌幅百分比 * @returns 颜色值 */ export function getChangeColor(changePercent: number | null | undefined): string { if (changePercent === null || changePercent === undefined) { return 'rgba(255, 255, 255, 0.6)'; } if (changePercent > 0) return '#EF4444'; // 红色(涨) if (changePercent < 0) return '#22C55E'; // 绿色(跌) return 'rgba(255, 255, 255, 0.6)'; // 灰色(平) } /** * 格式化涨跌幅显示 * @param changePercent 涨跌幅百分比 * @returns 格式化后的字符串(如 "+5.23%") */ export function formatChangePercent(changePercent: number | null | undefined): string { if (changePercent === null || changePercent === undefined) { return '--'; } const prefix = changePercent > 0 ? '+' : ''; return `${prefix}${Number(changePercent).toFixed(2)}%`; }