國際化(i18n)是讓軟體適應不同語言、地區、文化習慣的過程。許多開發者預設用戶使用美式英文、月/日/年日期格式、美元貨幣,導致非英語用戶遇到顯示錯誤、排序錯誤等問題。
toLocaleString() 格式固定,無法自訂輸出元件(如只顯示年月、不顯示星期)。locale(地區代碼),完全依賴瀏覽器預設。localeCompare() 排序介面不支援 Array.sort,且無法自訂排序規則。Intl 物件提供三大建構子,徹底解決上述問題:
Intl.DateTimeFormat:日期時間格式化Intl.NumberFormat:數字/貨幣/百分比格式化Intl.Collator:字串排序比較// 建立格式化器(支援多 locale 回退)
const dateFormatter = new Intl.DateTimeFormat('zh-TW', {
year: 'numeric', month: 'long', day: 'numeric',
weekday: 'long', hour: '2-digit', minute: '2-digit'
});
const numberFormatter = new Intl.NumberFormat('de-DE', {
style: 'currency', currency: 'EUR', minimumFractionDigits: 2
});
const collator = new Intl.Collator('zh-Hant-TW', {
usage: 'sort', sensitivity: 'variant'
});
// 使用
console.log(dateFormatter.format(new Date())); // 2024年12月25日 星期三 14:30
console.log(numberFormatter.format(1234.5)); // 1.234,50 €
console.log(['柏林', '北京', '上海'].sort(collator.compare)); // 依中文筆畫/拼音排序
| 選項 | 可用值 | 說明 |
|---|---|---|
| weekday, era | narrow, short, long | 星期/時代顯示長度 |
| month | 2-digit, numeric, narrow, short, long | 月份格式 |
| year, day, hour, minute, second | 2-digit, numeric | 數值格式 |
| timeZoneName | short, long | 時區名稱 |
| timeZone | IANA 時區代碼(如 Asia/Taipei) | 指定時區,預設為運行環境時區 |
| hour12 | true/false | 12/24 小時制 |
style:'decimal' | 'currency' | 'percent' | 'unit'currency:ISO 4217 貨幣代碼(如 'TWD', 'USD')minimumFractionDigits / maximumFractionDigits:小數位控制notation:'standard' | 'scientific' | 'engineering' | 'compact'usage:'sort' | 'search'sensitivity:'base' | 'accent' | 'case' | 'variant'ignorePunctuation:忽略標點符號numeric:啟用數字感知排序("2" < "10")// 泰文數字 + 中國農曆
const formatter = new Intl.DateTimeFormat('th-TH-u-ca-chinese-nu-thai', {
year: 'numeric', month: 'long', day: 'numeric'
});
console.log(formatter.format(new Date())); // 使用泰文數字顯示農曆日期
Intl 建構子會快取 locale 與選項解析結果。重複格式化時,務必重複使用同一實例:
// ❌ 慢:每次重新建構
items.map(item => new Intl.NumberFormat('zh-TW').format(item.price));
// ✅ 快:建構一次,重複使用
const fmt = new Intl.NumberFormat('zh-TW', {style: 'currency', currency: 'TWD'});
items.map(item => fmt.format(item.price));
['zh-Hant-TW', 'zh-CN', 'en-US'],瀏覽器會依序嘗試匹配。ECMAScript Intl API 為 JavaScript 帶來原生、高效能、高可配置的國際化能力。掌握 DateTimeFormat、NumberFormat、Collator 三大建構子及其選項,即可在前端完美處理日期、貨幣、排序等本地化需求,免除後端格式化往返成本,提升全球用戶體驗。