// 小程序各端对 new Date('YYYY-MM-DD') 的解析并不一致,纯日期统一按本地年月日构造。 function parseDate(value) { if (value instanceof Date) { return Number.isNaN(value.getTime()) ? null : value } if (!value) return null const text = String(value) const dateOnly = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text) if (dateOnly) { const year = Number(dateOnly[1]) const month = Number(dateOnly[2]) const day = Number(dateOnly[3]) const date = new Date(year, month - 1, day) if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) { return null } return date } const date = new Date(text) return Number.isNaN(date.getTime()) ? null : date } function pad(value) { return String(value).padStart(2, '0') } function formatDate(value, fallback = '') { const date = parseDate(value) if (!date) return fallback return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}` } function formatDateTime(value, fallback = '') { const date = parseDate(value) if (!date) return fallback return `${formatDate(date)} ${pad(date.getHours())}:${pad(date.getMinutes())}` } function calcAge(value) { const birth = parseDate(value) if (!birth) return 0 const today = new Date() let age = today.getFullYear() - birth.getFullYear() const monthDelta = today.getMonth() - birth.getMonth() if (monthDelta < 0 || (monthDelta === 0 && today.getDate() < birth.getDate())) age-- return age > 0 && age <= 120 ? age : 0 } function toISOString(value) { const date = parseDate(value) return date ? date.toISOString() : null } // 预约开始时间的最晚档位:所有服务统一可约到 23:30(整点/半点) const LATEST_APPOINTMENT_TIME = '23:30' // 预约时间只取整点和半点:按 30 分钟步长生成 start~end 内可选的 HH:mm 列表 function buildTimeSlots(start, end, stepMinutes = 30) { const startMinutes = parseTimeToMinutes(start) const endMinutes = parseTimeToMinutes(end) if (startMinutes === null || endMinutes === null || endMinutes < startMinutes) return [] const slots = [] // 起点若不在整/半点上,从之后最近的整/半点开始 let minutes = Math.ceil(startMinutes / stepMinutes) * stepMinutes while (minutes <= endMinutes) { slots.push(`${pad(Math.floor(minutes / 60))}:${pad(minutes % 60)}`) minutes += stepMinutes } return slots } function parseTimeToMinutes(value) { if (!value) return null const match = /^(\d{1,2}):(\d{2})$/.exec(String(value)) if (!match) return null const hour = Number(match[1]) const minute = Number(match[2]) if (hour > 23 || minute > 59) return null return hour * 60 + minute } module.exports = { parseDate, formatDate, formatDateTime, calcAge, toISOString, LATEST_APPOINTMENT_TIME, buildTimeSlots }