← 返回文章列表
JavaScript·249 次阅读

Intl API:原生国际化格式化的隐藏实力

Intl API:原生国际化格式化的隐藏实力

以前做日期格式化要么手写拼字符串,要么装 moment/dayjs。其实浏览器的 Intl 命名空间下藏着一整套格式化工具,很多场景根本不需要第三方库。

Intl.DateTimeFormat:日期时间

const date = new Date('2024-03-16T14:30:00')

new Intl.DateTimeFormat('zh-CN', { dateStyle: 'full', timeStyle: 'short' }).format(date)
// '2024年3月16日星期六 14:30'

new Intl.DateTimeFormat('en-US', { dateStyle: 'medium' }).format(date)
// 'Mar 16, 2024'

// 自定义字段
new Intl.DateTimeFormat('zh-CN', {
  year: 'numeric', month: 'long', day: 'numeric', weekday: 'short',
}).format(date)
// '2024年3月16日周六'

还支持时区转换(timeZone: 'America/New_York'),做跨时区展示时不用再手动加减小时。

Intl.NumberFormat:数字、货币、百分比

// 千分位
new Intl.NumberFormat('zh-CN').format(1234567.89) // '1,234,567.89'

// 货币
new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY' }).format(99.5)
// '¥99.50'
new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(99.5)
// '$99.50'

// 百分比与紧凑格式
new Intl.NumberFormat('zh-CN', { style: 'percent' }).format(0.856) // '86%'
new Intl.NumberFormat('zh-CN', { notation: 'compact' }).format(125000) // '12.5万'

notation: 'compact' 做数据大屏的数字缩写特别方便,中文自动出"万",英文出 "K/M"。

Intl.RelativeTimeFormat:相对时间

const rtf = new Intl.RelativeTimeFormat('zh-CN', { numeric: 'auto' })
rtf.format(-1, 'day')  // '昨天'
rtf.format(-3, 'hour') // '3小时前'
rtf.format(2, 'week')  // '2周后'

numeric: 'auto' 的妙处是 -1 天会显示"昨天"而不是"1天前",非常人性化。配合简单计算,评论区的"x 分钟前"一行搞定。

其他好用的成员

// ListFormat:列表连接
new Intl.ListFormat('zh-CN', { type: 'conjunction' }).format(['苹果', '香蕉', '橙子'])
// '苹果、香蕉和橙子'

// Collator:中文排序(按拼音)
['北京', '上海', '广州', '重庆'].sort(new Intl.Collator('zh-Hans-CN').compare)
// ['北京', '重庆', '广州', '上海']

// PluralRules:复数规则(i18n 场景)
new Intl.PluralRules('en').select(1) // 'one'
new Intl.PluralRules('en').select(2) // 'other'

中文排序这个特别实用——默认 sort 按 Unicode 码点排中文基本是乱的,Collator 一行解决。

性能提示:复用 formatter

构造 Intl 对象有开销,循环里每次 new 会很慢。正确姿势是构造一次反复用:

// 慢
list.forEach((item) => {
  console.log(new Intl.NumberFormat('zh-CN').format(item.value))
})

// 快
const fmt = new Intl.NumberFormat('zh-CN')
list.forEach((item) => {
  console.log(fmt.format(item.value))
})

小结

  • 日期时间:DateTimeFormat(含时区、dateStyle 预设)
  • 数字货币:NumberFormat(千分位、货币、紧凑缩写)
  • 相对时间:RelativeTimeFormat("昨天"这种自然表达)
  • 中文排序:Collator
  • 列表/复数:ListFormat、PluralRules

支持度早已全绿(IE11 都有基础支持)。下次再遇到格式化需求,先翻翻 Intl,大概率不用装新依赖。

看到这里了?如果这篇文章帮到过你

请我喝瓶可乐就好 🥤

收款码

评论0 条

还没有评论,来抢沙发~

发表评论

评论需审核后显示

© 2026 许冬博客 · 专注 JS 技术分享

·RSS 订阅·Powered by Nuxt 4