diff --git a/src/utils/format.ts b/src/utils/format.ts index 946c59c..488a6a9 100644 --- a/src/utils/format.ts +++ b/src/utils/format.ts @@ -1,14 +1,52 @@ // 通用格式化 / 校验纯函数(无状态,供 composable 与页面复用)。 -/** Date → `YYYY-MM-DD` */ -export const formatDate = (date: Date | string): string => { +/** Date 格式化。支持自定义格式,默认 `YYYY-MM-DD`。 + * + * 支持的 token: + * - YYYY / MM / DD / HH / mm / ss(补零) + * - M / D / H / m / s(不补零) + * + * @example + * formatDate(new Date()) // '2026-08-12' + * formatDate('2025-12-05', 'YYYY/MM/DD') // '2025/12/05' + * formatDate(date, 'YYYY-MM-DD HH:mm:ss') // '2026-08-12 09:05:30' + */ +export const formatDate = ( + date: Date | string, + format: string = "YYYY-MM-DD" +): string => { const transformedDate = typeof date === "string" ? new Date(date) : date; if (Number.isNaN(transformedDate.getTime())) return ""; const year = transformedDate.getFullYear(); - const month = String(transformedDate.getMonth() + 1).padStart(2, "0"); - const day = String(transformedDate.getDate()).padStart(2, "0"); - return `${year}-${month}-${day}`; + const month = transformedDate.getMonth() + 1; + const day = transformedDate.getDate(); + const hours = transformedDate.getHours(); + const minutes = transformedDate.getMinutes(); + const seconds = transformedDate.getSeconds(); + + const pad = (n: number) => String(n).padStart(2, "0"); + + // 按长度从长到短替换,避免短 token 干扰 + const replacements: Array<[string, string]> = [ + ["YYYY", String(year)], + ["MM", pad(month)], + ["DD", pad(day)], + ["HH", pad(hours)], + ["mm", pad(minutes)], + ["ss", pad(seconds)], + ["M", String(month)], + ["D", String(day)], + ["H", String(hours)], + ["m", String(minutes)], + ["s", String(seconds)], + ]; + + let result = format; + for (const [token, value] of replacements) { + result = result.split(token).join(value); + } + return result; }; /** 手机号输入格式化:仅保留数字并截断到 11 位。 */ diff --git a/src/views/reception/ReceptionTask.vue b/src/views/reception/ReceptionTask.vue index 45f06f6..8d07853 100644 --- a/src/views/reception/ReceptionTask.vue +++ b/src/views/reception/ReceptionTask.vue @@ -32,7 +32,7 @@
{{ item.studentName || "-" }} - 签到:{{ item.checkinTime }} + 签到:{{ formatDate(item.checkinTime, "MM-DD HH:mm:ss") }} = [ { label: "待接待", value: "available" },