// utils/dateUtils.js /** * 智能时间格式化:返回 "今天 18:00"、"昨天 18:00" 等 */ export function formatSmartTime(timeStr) { if (!timeStr) return '未知'; // iOS兼容格式 const safeStr = timeStr.replace(' ', 'T'); const inputDate = new Date(safeStr); if (isNaN(inputDate.getTime())) return '时间格式错误'; const now = new Date(); const inputDayStart = new Date(inputDate.getFullYear(), inputDate.getMonth(), inputDate.getDate()); const nowDayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()); const diffTime = nowDayStart - inputDayStart; const oneDay = 1000 * 60 * 60 * 24; const timePart = inputDate.toTimeString().slice(0, 5); // HH:mm if (diffTime === 0) { return `今天 ${timePart}`; } else if (diffTime === oneDay) { return `昨天 ${timePart}`; } else if (diffTime === oneDay * 2) { return `前天 ${timePart}`; } else { return `${inputDate.getMonth() + 1}月${inputDate.getDate()}日 ${timePart}`; } } /** * 相对时间格式化:返回 "刚刚更新"、"5分钟前更新"、"3天前更新" 等 */ export function formatDate(dateStr) { if (!dateStr) return '未知'; const parsedStr = dateStr.replace(' ', 'T'); const date = new Date(parsedStr); if (isNaN(date.getTime())) return '无效时间'; const now = new Date(); const diff = Math.floor((now - date) / 1000 / 60); // 单位:分钟 if (diff < 1) return '刚刚更新'; if (diff < 5) return '1分钟前更新'; if (diff < 10) return '5分钟前更新'; if (diff < 60) return `${diff}分钟前更新`; if (diff < 120) return '1小时前更新'; if (diff < 24 * 60) return `${Math.floor(diff / 60)}小时前更新`; if (diff < 7 * 24 * 60) return `${Math.floor(diff / (60 * 24))}天前更新`; return parsedStr.split('T')[0] + ' 更新'; } export function getFormattedTime() { const now = new Date(); const pad = n => n < 10 ? '0' + n : n; const year = now.getFullYear(); const month = pad(now.getMonth() + 1); const day = pad(now.getDate()); const hours = pad(now.getHours()); const minutes = pad(now.getMinutes()); const seconds = pad(now.getSeconds()); return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; }