Files
2026-09-11 01:45:04 +08:00

56 lines
1.8 KiB
TypeScript

// 金额 / 时间格式化工具
function pad(n: number): string {
return n < 10 ? `0${n}` : `${n}`
}
// 金额(分)转「¥xx.xx」字符串
export function fenToYuan(fen: number | null | undefined): string {
if (fen === null || fen === undefined || isNaN(fen)) return '¥0.00'
return `¥${(fen / 100).toFixed(2)}`
}
// 秒级时间戳转 YYYY-MM-DD
export function formatDate(seconds: number | null | undefined): string {
if (!seconds) return ''
const d = new Date(seconds * 1000)
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
}
// 秒级时间戳转 YYYY-MM-DD HH:mm
export function formatDateTime(seconds: number | null | undefined): string {
if (!seconds) return ''
const d = new Date(seconds * 1000)
return `${formatDate(seconds)} ${pad(d.getHours())}:${pad(d.getMinutes())}`
}
// 相对时间:刚刚 / x分钟前 / x小时前 / 今天 / YYYY-MM-DD
export function formatRelativeTime(seconds: number | null | undefined): string {
if (!seconds) return ''
const now = Math.floor(Date.now() / 1000)
const diff = now - seconds
if (diff < 0) return formatDate(seconds)
if (diff < 60) return '刚刚'
if (diff < 3600) return `${Math.floor(diff / 60)} 分钟前`
const d = new Date(seconds * 1000)
const today = new Date()
const isToday =
d.getFullYear() === today.getFullYear() &&
d.getMonth() === today.getMonth() &&
d.getDate() === today.getDate()
if (diff < 86400) {
return isToday ? '今天' : `${Math.floor(diff / 3600)} 小时前`
}
return formatDate(seconds)
}
// 支付倒计时(秒)转 mm:ss
export function formatCountdown(totalSeconds: number): string {
if (totalSeconds <= 0) return '00:00'
const m = Math.floor(totalSeconds / 60)
const s = Math.floor(totalSeconds % 60)
return `${pad(m)}:${pad(s)}`
}