* 格式化时间戳为可读日期字符串
* @param ts 毫秒时间戳
* @param fmt 格式模板,默认 'YYYY-MM-DD HH:mm:ss'
*/
export function formatTimestamp(ts: number | string | undefined | null, fmt: string = 'YYYY-MM-DD HH:mm:ss'): string {
if (!ts || ts === 0) return '-'
const d = new Date(typeof ts === 'string' ? parseInt(ts) : ts)
if (isNaN(d.getTime())) return '-'
const pad = (n: number) => n < 10 ? '0' + n : String(n)
return fmt
.replace('YYYY', String(d.getFullYear()))
.replace('MM', pad(d.getMonth() + 1))
.replace('DD', pad(d.getDate()))
.replace('HH', pad(d.getHours()))
.replace('mm', pad(d.getMinutes()))
.replace('ss', pad(d.getSeconds()))
}
* 格式化日期(不含时间)
*/
export function formatDate(ts: number | string | undefined | null): string {
return formatTimestamp(ts, 'YYYY-MM-DD')
}
* 相对时间(如 "3 分钟前")
*/
export function formatRelative(ts: number | string | undefined | null): string {
if (!ts || ts === 0) return '-'
const d = new Date(typeof ts === 'string' ? parseInt(ts) : ts)
if (isNaN(d.getTime())) return '-'
const diff = Date.now() - d.getTime()
const seconds = Math.floor(diff / 1000)
const minutes = Math.floor(seconds / 60)
const hours = Math.floor(minutes / 60)
const days = Math.floor(hours / 24)
if (days > 30) return formatTimestamp(ts)
if (days > 0) return `${days} 天前`
if (hours > 0) return `${hours} 小时前`
if (minutes > 0) return `${minutes} 分钟前`
return '刚刚'
}