import { format, parseISO, isValid } from "date-fns"; /** * 格式化日期字串為統一格式 (YYYY-MM-DD HH:mm:ss) * @param dateStr ISO 格式的日期字串 * @param formatStr 輸出的格式字串,預設為 "yyyy-MM-dd HH:mm:ss" * @returns 格式化後的字串,若日期無效則回傳空字串 */ export function formatDate( dateStr: string | null | undefined, formatStr?: string ): string { if (!dateStr) return "-"; try { const date = parseISO(dateStr); if (!isValid(date)) return "-"; // 如果使用者有指定格式,則依指定格式輸出 if (formatStr) { return format(date, formatStr); } // 智慧判斷:如果時間是 00:00:00 (通常代表後端僅提供日期),則僅顯示日期 const hasTime = date.getHours() !== 0 || date.getMinutes() !== 0 || date.getSeconds() !== 0; return format(date, hasTime ? "yyyy-MM-dd HH:mm:ss" : "yyyy-MM-dd"); } catch (e) { return "-"; } } /** * 格式化日期字串為僅日期格式 (YYYY-MM-DD) */ export function formatDateOnly(dateStr: string | null | undefined): string { return formatDate(dateStr, "yyyy-MM-dd"); }