intl
API 是 ECMAScript 的一部分,现代浏览器和 Node.js 环境中已经内置,无需安装。但对于旧版环境,可以通过 polyfill 添加支持。
安装 polyfill
npm install intl
格式化日期和时间
const date = new Date(Date.UTC(2024, 5, 26, 19, 0, 0));
// 英文格式
console.log(new Intl.DateTimeFormat('en-US').format(date));
// 输出: 6/26/2024
// 中文格式
console.log(new Intl.DateTimeFormat('zh-CN').format(date));
// 输出: 2024/6/26
格式化数字
const number = 123456.789;
// 英文格式
console.log(new Intl.NumberFormat('en-US').format(number));
// 输出: 123,456.789
// 中文格式
console.log(new Intl.NumberFormat('zh-CN').format(number));
// 输出: 123,456.789
格式化货币
const price = 1000;
// 美元格式
console.log(new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(price));
// 输出: $1,000.00
// 欧元格式
console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(price));
// 输出: 1.000,00 €
Intl.DateTimeFormat:格式化日期和时间。
new Intl.DateTimeFormat(locale, options)
:创建格式化对象。format(date)
:格式化日期。Intl.NumberFormat:格式化数字。
new Intl.NumberFormat(locale, options)
:创建格式化对象。format(number)
:格式化数字。Intl.Collator:字符串比较。
new Intl.Collator(locale, options)
:创建比较对象。compare(string1, string2)
:比较两个字符串。Intl.RelativeTimeFormat:格式化相对时间。
new Intl.RelativeTimeFormat(locale, options)
:创建格式化对象。format(value, unit)
:格式化相对时间。Intl.PluralRules:确定复数形式。
new Intl.PluralRules(locale, options)
:创建规则对象。select(number)
:确定复数形式。使用 polyfill 添加对旧浏览器的支持
import 'intl';
import 'intl/locale-data/jsonp/en';
import 'intl/locale-data/jsonp/zh';
// 然后可以像现代浏览器一样使用 Intl API
const date = new Date(Date.UTC(2024, 5, 26, 19, 0, 0));
console.log(new Intl.DateTimeFormat('en-US').format(date));
自定义区域数据
可以通过自定义区域数据来扩展 Intl
的功能:
const customData = {
data: {
en: {
units: {
temperature: {
short: {
Celsius: { symbol: '℃', style: 'unit', unitDisplay: 'short' },
},
},
},
},
},
};
// 使用 customData 自定义区域数据
const formatter = new Intl.NumberFormat('en', customData);
console.log(formatter.format(25)); // 输出: 25℃