变更预识别修改

This commit is contained in:
2026-09-11 12:02:46 +08:00
parent 7030414146
commit 1c4c8e7b62
12 changed files with 376 additions and 85 deletions
+60
View File
@@ -97,6 +97,66 @@ export function formatTimestamp(timestamp: number | string | Date | null,format:
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
/**
* 任意时间格式 → 时间戳(支持 只有小时)
* @param {string|number|Date} input
* @param {'ms'|'s'} unit 默认毫秒
*/
export function anyToTimestamp(input: string | number | Date | null | undefined, unit = 'ms') {
if (input == null || input === '') return null;
const toResult = (ms: number) =>
Number.isNaN(ms) ? null : unit === 's' ? Math.floor(ms / 1000) : ms;
// 1. 数字
if (typeof input === 'number') return toResult(input);
// 2. Date
if (input instanceof Date) return toResult(input.getTime());
let str = String(input).trim();
// 3. 纯数字字符串
if (/^\d+$/.test(str)) return toResult(Number(str));
// 4. 统一分隔符
str = str
.replace(/[年月]/g, '-')
.replace(/[日号]/g, '')
.replace(/[时分]/g, ':')
.replace(/秒/g, '')
.replace(/[./]/g, '-')
.replace(/\s+/g, ' ')
.trim();
// 5. 手动解析:小时、分钟、秒、毫秒全部可选
const m = str.match(
/^(\d{4})-(\d{1,2})-(\d{1,2})(?:[ T](\d{1,2}))?(?::(\d{1,2}))?(?::(\d{1,2}))?(?:\.(\d{1,3}))?/
);
if (m) {
const [, y, mo, d, h = '0', mi = '0', s = '0', ms = '0'] = m;
const t = new Date(
+y,
+mo - 1,
+d,
+h,
+mi,
+s,
+ms.padEnd(3, '0')
).getTime();
if (!Number.isNaN(t)) return toResult(t);
}
// 6. 兜底
let t = new Date(str.replace(' ', 'T')).getTime();
if (!Number.isNaN(t)) return toResult(t);
t = Date.parse(str);
if (!Number.isNaN(t)) return toResult(t);
return null;
};
// 辅助函数:Fisher-Yates 洗牌算法
function shuffle(arr:any) {
for (let i = arr.length - 1; i > 0; i--) {