函数: timeAgo()
ts
function timeAgo(time?): string;定义于: date.ts:92
计算传入时间距当前时刻的间隔,转为「刚刚 / x分钟前 / x小时前 / x天前 / x个月前 / x年前」的相对描述。
参数
| 参数 | 类型 | 描述 |
|---|---|---|
time | string | number | Date | 待计算的时间,默认取当前时间 Date.now()。支持三种形式: - number:时间戳,自动兼容 10 位(秒)与 13 位(毫秒); - string:可被 new Date() 解析的时间字符串; - Date:时间对象。 |
返回值
string
相对时间描述字符串;无法解析出有效时间时返回 ''。
备注
分档规则:小于 60 秒返回 '刚刚',随后依次按分钟、小时、天、月、年逐级换算, 其中月按 30 天、年按 12 个月粗略估算。
示例
ts
timeAgo(Date.now() - 30_000) // => '刚刚'
timeAgo(Date.now() - 60_000) // => '1分钟前'
timeAgo(Date.now() - 3 * 3600_000) // => '3小时前'
timeAgo('invalid') // => ''参见
formatTime 若需要精确的日期格式而非相对时间。