跳到主要内容

js 的 Intl 相对时间格式化

· 阅读需 1 分钟
Slipeda

JavaScript 中的 Intl.RelativeTimeFormat() API 可用于获取人类可读的日期差异。

  • 时间负差
const olderDate = new Date('2022-10-31')
const currentDate = new Date('2022-11-01')

const diff = olderDate - currentDate

const formatter = new Intl.RelativeTimeFormat('en', { numeric: 'auto' })
console.log(formatter.format(Math.round(diff / 86400000), 'day'))
// yesterday
  • numeric 参数
const formatter = new Intl.RelativeTimeFormat('en', {
numeric: 'always',
})

console.log(formatter.format(Math.round(diff / 86400000), 'day'))
// 1 day ago
  • 时间正差
const formatter = new Intl.RelativeTimeFormat('en', {
numeric: 'auto',
style: 'long',
localeMatcher: 'best fit',
})

console.log(formatter.format(Math.round(diff / 86400000), 'day'))
// tomorrow

原文: Human-readable date difference in JavaScript