Files
ai_academy/frontend/src/utils/datetime.ts
T

54 lines
2.0 KiB
TypeScript

// 统一时间展示口径:全部按北京时间(Asia/Shanghai)格式化,页面展示不带秒。
// 后端时间戳带原时区偏移,new Date 均可正确解析,再统一投到北京时区输出。
const BEIJING_DATETIME = new Intl.DateTimeFormat('zh-CN', {
timeZone: 'Asia/Shanghai',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hour12: false,
})
const BEIJING_CLOCK = new Intl.DateTimeFormat('zh-CN', {
timeZone: 'Asia/Shanghai',
hour: '2-digit',
minute: '2-digit',
hour12: false,
})
const BEIJING_DATETIME_SEC = new Intl.DateTimeFormat('zh-CN', {
timeZone: 'Asia/Shanghai',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
})
/** fmtBeijingTime 任意时间戳 → 北京时间「YYYY/MM/DD HH:mm」(无秒);空/非法输入返回空串。 */
export function fmtBeijingTime(raw: string | number | Date | null | undefined): string {
if (raw === null || raw === undefined || raw === '') return ''
const date = raw instanceof Date ? raw : new Date(raw)
if (Number.isNaN(date.getTime())) return ''
return BEIJING_DATETIME.format(date)
}
/** fmtBeijingClock 北京时间「HH:mm」(无秒),通知横幅等紧凑场景用。 */
export function fmtBeijingClock(raw: string | number | Date | null | undefined): string {
if (raw === null || raw === undefined || raw === '') return ''
const date = raw instanceof Date ? raw : new Date(raw)
if (Number.isNaN(date.getTime())) return ''
return BEIJING_CLOCK.format(date)
}
/** fmtBeijingTimeSec 北京时间「YYYY/MM/DD HH:mm:ss」(带秒;签到明细等需秒级精度的场景)。 */
export function fmtBeijingTimeSec(raw: string | number | Date | null | undefined): string {
if (raw === null || raw === undefined || raw === '') return ''
const date = raw instanceof Date ? raw : new Date(raw)
if (Number.isNaN(date.getTime())) return ''
return BEIJING_DATETIME_SEC.format(date)
}