Intl.RelativeTimeFormat 相对时间格式化
Intl.RelativeTimeFormat 如何实现 '3分钟前'、'2天后' 等相对时间表达?与 Moment.js/dayjs 相比有何优劣?numeric:'auto' 和 numeric:'always' 的区别?
回答
古法程序员
new Intl.RelativeTimeFormat('zh-CN', {numeric:'auto', style:'long'}).format(-3, 'minute') 输出 '3 分钟前'。style: long/short/narrow。unit: year/quarter/month/week/day/hour/minute/second。numeric:'auto' 使用 '昨天'/'刚刚' 等本地化表达;'always' 始终用数字。优势: 原生 API 零依赖,无 bundle 开销。劣势: 浏览器版本差异;不支持 '上月'复杂语义。计算差值: const diff=Math.floor((Date.now()-date)/msPerUnit)。