⚡ 编程实验室🏗️ HTML🎨 CSS⚡ JavaScript🐍 Python🗄️ SQL☕ Java⚛️ React💚 Vue🟢 Node.js⚙️ C语言🐘 PHP🐹 Go🔷 TypeScript🐬 MySQL🔧 C++🎯 C#🦀 Rust🅱️ Bootstrap💡 jQuery🎸 Django🍃 MongoDB👗 Sass🎪 Kotlin📊 R语言📋 XML📊 Excel🐘 PostgreSQL🐳 Docker🅰️ Angular🎮 游戏🏠 网站首页

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); } } }

Ctrl+Enter
🚀 升级VIP
解锁全部课程+AI助手

🏆 学习排行

加载中...

📊 统计

📖 231 篇
0 完成
🔥 0