Intl.Locale 与相对时间格式化:超越 toLocaleString 的国际化利器
利用 Intl.Locale 解析和操作区域设置,结合 Intl.RelativeTimeFormat 实现智能的时间描述。 · 难度:入门 · +10XP
Intl.Locale 与相对时间格式化:超越 toLocaleString 的国际化利器
你以为国际化就是 toLocaleString?Intl 对象提供了一整套语言敏感 API。本课程聚焦 Intl.Locale(解析和构建 BCP 47 语言标签)和 Intl.RelativeTimeFormat(生成'3 days ago'、'in 2 months'等自然语言时间)。你将学会处理区域回退、自定义日历、数字系统、时区转换,以及结合 Intl.DateTimeFormat 实现绝对与相对时间的混合展示。这些 API 为多语言应用提供了官方的、高性能的解决方案,无需引入 moment.js。
const locale = new Intl.Locale('zh-CN-u-ca-chinese-hc-h12');
console.log(locale.calendar); // 'chinese'
console.log(locale.hourCycle); // 'h12'
const rtf = new Intl.RelativeTimeFormat('zh-CN', { numeric: 'always' });
console.log(rtf.format(-3, 'day')); // '3天前'
console.log(rtf.format(10, 'minute')); // '10分钟后'
// 更高级的用法:智能选择单位
function timeAgo(date) {
const now = Date.now();
const diff = (now - date) / 1000;
const units = [
[60, 'second'],
[3600, 'minute'],
[86400, 'hour'],
[2592000, 'day'],
[31536000, 'month'],
];
for (const [threshold, unit] of units) {
if (Math.abs(diff) < threshold) {
const value = Math.round(diff / (threshold / 60));
return rtf.format(value, unit);
}
}
}