41 lines
1.0 KiB
JavaScript
41 lines
1.0 KiB
JavaScript
/**
|
|
* 时间格式化工具
|
|
*/
|
|
|
|
/**
|
|
* 将毫秒时间戳格式化为相对时间字符串
|
|
* - < 60s → "刚刚"
|
|
* - < 60min → "X 分钟前"
|
|
* - < 24h → "X 小时前"
|
|
* - < 7day → "X 天前"
|
|
* - >= 7day → 格式化为 YYYY-MM-DD
|
|
*
|
|
* @param {number} ms 毫秒时间戳
|
|
* @returns {string} 相对时间字符串
|
|
*/
|
|
export function formatRelativeTime(ms) {
|
|
if (!ms || typeof ms !== 'number' || ms <= 0) return ''
|
|
|
|
const now = Date.now()
|
|
const diff = Math.max(0, now - ms)
|
|
|
|
const sec = Math.floor(diff / 1000)
|
|
if (sec < 60) return '刚刚'
|
|
|
|
const min = Math.floor(sec / 60)
|
|
if (min < 60) return `${min} 分钟前`
|
|
|
|
const hr = Math.floor(min / 60)
|
|
if (hr < 24) return `${hr} 小时前`
|
|
|
|
const day = Math.floor(hr / 24)
|
|
if (day < 7) return `${day} 天前`
|
|
|
|
// 7 天及以上显示日期
|
|
const d = new Date(ms)
|
|
const y = d.getFullYear()
|
|
const m = String(d.getMonth() + 1).padStart(2, '0')
|
|
const dd = String(d.getDate()).padStart(2, '0')
|
|
return `${y}-${m}-${dd}`
|
|
}
|