let list = [1, 2, 3, 10, 11, 12, 20, 21, 22, 100, 102, 103, 200, 201, 202, 130, 220];
// numeric: 是否按照数值进行比较
let collator = Intl.Collator(undefined, { numeric: true });
list.sort(); // [ 1, 10, 100, 102, 103, 11, 12, 130, 2, 20, 200, 201, 202, 21, 22, 220, 3 ]
list.sort(collator.compare); // [ 1, 2, 3, 10, 11, 12, 20, 21, 22, 100, 102, 103, 130, 200, 201, 202, 220 ]
let namelist = [
'陈坤',
'邓超',
'杜淳',
'冯绍峰',
'韩庚',
'胡歌',
'黄晓明',
'贾乃亮',
'李晨',
'李易峰',
'鹿晗',
'井柏然',
'刘烨',
'陆毅',
'孙红雷'
];
namelist.sort(); // [ '井柏然', '冯绍峰', '刘烨', '孙红雷', '李易峰', '李晨', '杜淳', '胡歌', '贾乃亮', '邓超', '陆毅', '陈坤', '韩庚', '鹿晗', '黄晓明' ]
namelist.sort(new Intl.Collator('zh').compare); // [ '陈坤', '邓超', '杜淳', '冯绍峰', '韩庚', '胡歌', '黄晓明', '贾乃亮', '井柏然', '李晨', '李易峰', '刘烨', '陆毅', '鹿晗', '孙红雷' ]
const format = new Intl.DateTimeFormat('zh-Hans', {
year: 'numeric',
month: '2-digit',
// weekday: 'long',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
})
// 创建一个新的 DateTimeFormat 实例
const format2 = new Intl.DateTimeFormat('zh-CN', {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
});
// 格式化当前日期和时间
format.format(new Date()); // '2024/05/25 17:06:02'
format2.format(new Date()); // '2024年5月25日 17:06:24'
// 让对语言敏感的列表进行格式化
var vehicles = ['Motorcycle', 'Bus', 'Car'];
var formatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
console.log(formatter.format(vehicles)); // 'Motorcycle, Bus, and Car'
Intl.NumberFormat(undefined, {
minimumFractionDigits: 10
}).format(123456789056.123); // '123,456,789,056.1230000000'
new Intl.NumberFormat('zh-Hans', {
style: 'currency',
currency: 'CNY',
currencyDisplay: 'name'
}).format(12345.6789); // '12,345.68人民币'
'星期' + new Intl.NumberFormat('zh-Hans-CN-u-nu-hanidec').format(new Date().getDay()); // '星期六'
new Intl.NumberFormat('zh-Hans-CN-u-nu-hanidec', {
style: 'currency',
currency: 'CNY',
currencyDisplay: 'name',
useGrouping: false
}).format(1234); // '一二三四.〇〇人民币'
new Intl.PluralRules('ar-EG').select(0);
// → 'zero'
new Intl.PluralRules('ar-EG').select(1);
// → 'one'
new Intl.PluralRules('ar-EG').select(2);
// → 'two'
new Intl.PluralRules('ar-EG').select(6);
// → 'few'
new Intl.PluralRules('ar-EG').select(18);
// → 'many'
let rtf = new Intl.RelativeTimeFormat('zh', {
numeric: 'auto'
});
// -1表示前一天
rtf.format(-1, 'day'); // '昨天'
rtf.format(1, 'day'); // '明天'
rtf.format(-365, 'day'); // '365天前'
Intl.getCanonicalLocales('zh-hans');
// 结果是:["zh-Hans"]
Intl.getCanonicalLocales('zh');
// 结果是:["zh"]
Intl.getCanonicalLocales('zh-cmn-Hans-CN');
// 结果是:["cmn-Hans-CN"]
Intl.getCanonicalLocales('zh-cn');
// 结果是:["zh-CN"]
Intl.getCanonicalLocales('yue-hk');
// 结果是:["yue-HK"]
Intl.getCanonicalLocales('zh-some');
// 结果是:["zh-Some"]