/** * 将 UTC ISO 字符串转换为北京时间(UTC+8)的日期/日期时间字符串 */ const BJ_OFFSET = 8 * 60 * 60 * 1000 // UTC+8 function _parse(iso: string | null | undefined): Date | null { if (!iso) return null const d = new Date(iso) return isNaN(d.getTime()) ? null : d } /** "2026-07-11" */ export function toBeijingDate(iso: string | null | undefined): string { const d = _parse(iso) if (!d) return '' return new Date(d.getTime() + BJ_OFFSET).toISOString().slice(0, 10) } /** "2026-07-11 20:30" */ export function toBeijingDateTime(iso: string | null | undefined): string { const d = _parse(iso) if (!d) return '' return new Date(d.getTime() + BJ_OFFSET).toISOString().slice(0, 16).replace('T', ' ') } /** "2026-07-11 20:30" (别名) */ export const formatDateTime = toBeijingDateTime /** 相对时间:刚刚 / N 分钟前 / N 小时前 / N 天前 */ export function relativeTime(iso: string | null | undefined): string { if (!iso) return '' const diff = Math.floor((Date.now() - new Date(iso).getTime()) / 1000) if (diff < 60) return '刚刚' if (diff < 3600) return `${Math.floor(diff / 60)} 分钟前` if (diff < 86400) return `${Math.floor(diff / 3600)} 小时前` if (diff < 2592000) return `${Math.floor(diff / 86400)} 天前` return iso.slice(0, 10) }