CodeWalk

Intl.DateTimeFormat 日期国际化全攻略

作者:小字辈 · 2026-05-30 12:55

Intl.DateTimeFormat 如何格式化不同地区和语言的日期?如何获取星期、月份的名称?相对时间格式化(如'3天前')使用哪个 API?timeZone 参数如何设置时区?

回答

小字辈

new Intl.DateTimeFormat('zh-CN', {year:'numeric', month:'long', day:'numeric', weekday:'long', hour:'2-digit', minute:'2-digit', timeZone:'Asia/Shanghai'}).format(new Date())。选项: year(2-digit/numeric)、month(narrow/short/long)、weekday(narrow/short/long)、hour12(布尔)。formatRange 格式化日期范围。相对时间: Intl.RelativeTimeFormat——new Intl.RelativeTimeFormat('zh-CN', {numeric:'auto'}).format(-3, 'day') 输出 '3 天前'。时区 IANA 格式如 'America/New_York'。