Files
zkxw/web-admin/src/utils/datetime-display.ts
T
2026-06-30 16:48:52 +08:00

48 lines
1.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/** 是否形如 ISO / 空格分隔的日期时间字符串 */
export function looksLikeDateTime(value: unknown): boolean {
const s = String(value ?? '').trim()
return /^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2})?/.test(s)
}
/**
* 展示用日期时间:若时分秒均为 0(或无时间部分)则只显示 YYYY-MM-DD;
* 否则保留有意义的时间部分。
*/
export function formatDateTimeDisplay(value: string | number | null | undefined): string {
const s = String(value ?? '').trim()
if (!s) return ''
if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return s
const m = s.match(
/^(\d{4}-\d{2}-\d{2})[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?$/
)
if (m) {
const [, date, hh, mm, ss = '00'] = m
if (hh === '00' && mm === '00' && ss.startsWith('00')) {
return date
}
if (ss && ss !== '00') {
return `${date} ${hh}:${mm}:${ss.slice(0, 2)}`
}
return `${date} ${hh}:${mm}`
}
return s
}
/** 纯日期字段:始终只展示 YYYY-MM-DD(兼容后端带 00:00:00 的历史数据) */
export function formatDateOnly(value: string | number | null | undefined): string {
const s = String(value ?? '').trim()
if (!s) return ''
return s.length >= 10 ? s.slice(0, 10) : s
}
/** 通用展示:空值 → —;日期时间按 formatDateTimeDisplay 处理 */
export function formatDisplayOrDash(value: unknown): string {
if (value === null || value === undefined || value === '') return '—'
if (typeof value === 'boolean') return value ? '是' : '否'
const s = String(value)
return looksLikeDateTime(s) ? formatDateTimeDisplay(s) || '—' : s
}