/** * 日期时间工具 */ /** * 格式化时间戳/日期为指定格式 * y=年 M=月 d=日 h=时 m=分 s=秒(月日时分秒不足两位补零) */ export function format(format: string, time?: number) { const now = time ? new Date(time) : new Date(); const map: Record = { y: now.getFullYear(), M: now.getMonth() + 1 > 9 ? now.getMonth() + 1 : `0${now.getMonth() + 1}`, d: now.getDate() > 9 ? now.getDate() : `0${now.getDate()}`, h: now.getHours() > 9 ? now.getHours() : `0${now.getHours()}`, m: now.getMinutes() > 9 ? now.getMinutes() : `0${now.getMinutes()}`, s: now.getSeconds() > 9 ? now.getSeconds() : `0${now.getSeconds()}`, }; const res = []; for (let i = 0; i < format.length; i++) { if (map[format.charAt(i)]) { res.push(map[format.charAt(i)]); } else { res.push(format.charAt(i)); } } return res.join(""); } /** * iOS 安全的日期解析:兼容 "2026-01-01 10:00:00" 格式(iOS 不支持 "-" 分隔) */ export function parseDate(str: string | number | Date): Date { if (str instanceof Date) { return str; } if (typeof str === "number") { return new Date(str); } return new Date(String(str || "").replace(/-/g, "/")); } /** * 充电时长格式化:"x小时y分钟" 或 "y分钟" * @param minMinutes 最小时长(分钟),用于修正起止时间异常时显示 0 分钟 */ export function formatDuration(start: string | number | Date, end: string | number | Date, minMinutes = 0): string { const startTime = parseDate(start).getTime(); const endTime = parseDate(end).getTime(); let diff = parseInt(`${(endTime - startTime) / 1000}`); if (Number.isNaN(diff) || diff < 0) { diff = 0; } const min = parseInt(`${diff / 60}`); return formatDurationMinutes(Math.max(min, minMinutes)); } function formatDurationMinutes(min: number): string { return min >= 60 ? `${parseInt(`${min / 60}`)}小时${parseInt(`${min - parseInt(`${min / 60}`) * 60}`)}分钟` : `${min}分钟`; }