/** * 统一日期时间格式化工具(platform 端) * * 后端(Go)返回的时间字段为 RFC3339 / ISO 8601 字符串, * 例如 "2026-03-31T23:34:07+08:00",直接渲染不友好。 * 页面上显示时间统一使用本工具,输出: * formatDateTime / formatTime -> 2026-03-31 23:34:07(YYYY-MM-DD HH:mm:ss) * formatDate / formatDateOnly -> 2026-03-31(YYYY-MM-DD) */ const pad = (n: number) => String(n).padStart(2, "0"); function toDate(value: any): Date | null { if (value === null || value === undefined || value === "") return null; if (value instanceof Date) return isNaN(value.getTime()) ? null : value; // 兼容秒级 / 毫秒级时间戳 if (typeof value === "number") { const d = new Date(value < 1e12 ? value * 1000 : value); return isNaN(d.getTime()) ? null : d; } // "2026-03-31 23:34:07" 形式在部分浏览器解析异常,统一先替换为 ISO 形式 const str = String(value).trim().replace(" ", "T"); const d = new Date(str); return isNaN(d.getTime()) ? null : d; } /** 2026-03-31 23:34:07(YYYY-MM-DD HH:mm:ss);非法值返回 "-" */ export function formatDateTime(value: any): string { const d = toDate(value); if (!d) return "-"; return ( `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ` + `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}` ); } /** 与 formatDateTime 相同(兼容旧调用名) */ export function formatTime(value: any): string { return formatDateTime(value); } /** 2026-03-31(YYYY-MM-DD);非法值返回 "-";纯日期串不做时区换算 */ export function formatDate(value: any): string { if (typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value.trim())) { return value.trim(); } const d = toDate(value); if (!d) return "-"; return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`; } /** 与 formatDate 相同(兼容旧调用名) */ export function formatDateOnly(value: any): string { return formatDate(value); }