export default { // 格式化时间函数 getTime(format = "YYYY-MM-DD hh:mm:ss", date = new Date()) { const pad = (num, len = 2) => num.toString().padStart(len, "0"); const parts = { YYYY: date.getFullYear().toString(), MM: pad(date.getMonth() + 1), DD: pad(date.getDate()), hh: pad(date.getHours()), mm: pad(date.getMinutes()), ss: pad(date.getSeconds()) }; // 分组规则:日期部分和时间部分分别检查 const datePattern = /(YYYY)([^A-Za-z]?)(MM)([^A-Za-z]?)(DD)?/; const timePattern = /(hh)([^A-Za-z]?)(mm)([^A-Za-z]?)(ss)?/; // 检查日期部分 const dateMatch = format.match(datePattern); if (dateMatch) { const dateSeps = [dateMatch[2], dateMatch[4]].filter(Boolean); if (new Set(dateSeps).size > 1) { console.error( `❌ 格式错误:日期部分存在多种连接符 (${dateSeps.join(", ")})。\n👉 解决方案:请统一日期部分的连接符,例如 "YYYY-MM-DD" 或 "YYYY/MM/DD"` ); return ""; } } // 检查时间部分 const timeMatch = format.match(timePattern); if (timeMatch) { const timeSeps = [timeMatch[2], timeMatch[4]].filter(Boolean); if (new Set(timeSeps).size > 1) { console.error( `❌ 格式错误:时间部分存在多种连接符 (${timeSeps.join(", ")})。\n👉 解决方案:请统一时间部分的连接符,例如 "hh:mm:ss" 或 "hh-mm-ss"` ); return ""; } } // 替换格式 let result = format; for (const key in parts) { result = result.replace(new RegExp(key, "g"), parts[key]); } return result; }, // 获取北京时间 getBeijingTime(date = new Date()) { const f = n => String(n).padStart(2, '0'); const t = new Date(date.toLocaleString('en-US', { timeZone: 'Asia/Shanghai' })); return `${t.getFullYear()}-${f(t.getMonth()+1)}-${f(t.getDate())} ${f(t.getHours())}:${f(t.getMinutes())}:${f(t.getSeconds())}`; } }