From 109b42257ed554008f62b54a8be3ce8173a418f2 Mon Sep 17 00:00:00 2001 From: lison Date: Fri, 26 Sep 2025 16:11:05 +0000 Subject: [PATCH] =?UTF-8?q?update=20Web/src/utils/formatTime.ts.=20?= =?UTF-8?q?=E5=AF=B9=E6=8E=A5=E7=9A=84=E5=BE=88=E5=A4=9A=E7=B3=BB=E7=BB=9F?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E5=BA=93=E6=97=B6=E9=97=B4=E9=83=BD=E6=98=AF?= =?UTF-8?q?yyyyMMddHHmmss=E8=BF=99=E7=A7=8D=E6=A0=BC=E5=BC=8F=E7=9A=84?= =?UTF-8?q?=EF=BC=8C=E6=AF=8F=E6=AC=A1=E9=83=BD=E8=A6=81=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E4=B8=8B=E8=BF=99=E4=B8=AA=E6=96=B9=E6=B3=95=EF=BC=8C=E5=B9=B2?= =?UTF-8?q?=E8=84=86=E7=9B=B4=E6=8E=A5pr=20:)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: lison --- Web/src/utils/formatTime.ts | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/Web/src/utils/formatTime.ts b/Web/src/utils/formatTime.ts index a35f31b03..141ed05d9 100644 --- a/Web/src/utils/formatTime.ts +++ b/Web/src/utils/formatTime.ts @@ -179,3 +179,40 @@ export function formatTimeDiff(dateBegin: Date, dateEnd: Date,) { } return result; } + +/** + * 将时间字符串格式化为 `YYYY-mm-dd HH:MM:SS` 格式 + * @param timeStr 时间字符串,支持非时区格式,如 `YYYYmmdd`、`YYYYmmddHH`、`YYYYmmddHHMM`、`YYYYmmddHHMMSS`、`YYYY/mm/dd`、`YYYY年mm月dd日`等 + * @param length 返回的时间字符串长度,默认0表示自动识别长度 + * @returns 返回格式化后的时间字符串 + */ +export function formatDateString(timeStr: string | null | undefined, length: number = 0): string { + if (!timeStr) return ''; + + let str = timeStr.replace(/\D/g, ''); + let len = str.length; + + if (len <= 4) return str; + + // 处理奇数长度:在最后一位前补0 + if (len & 1) { + len++; + str = str.slice(0, -1) + '0' + str.slice(-1); + } + + str = str.padEnd(14, '0'); + + // 提取各时间部分 + const [year, month, day, hour, minute, second] = [0, 4, 6, 8, 10, 12].map(index => str.slice(index, (index || 2) + 2)); + + // 计算长度,长度为10时,显示分钟 + const targetLength = length > 0 ? length : len + (len - 4) / 2 + (len == 10 ? 3 : 0); + + // 处理0/00的修正函数 + const fixZero = (value: string) => ['0', '00'].includes(value) ? '01' : value; + + // 生成完整格式字符串 + const fullFormat = `${year}-${fixZero(month)}-${fixZero(day)} ${hour}:${minute}:${second}`; + + return fullFormat.slice(0, targetLength); +} \ No newline at end of file -- Gitee