获取所有语言、时区、币种数据
汇率数据
需从OA那里获取
日期格式化
Intl是浏览器内置的国际化接口,各大主流浏览器均支持,它的很多用法可以自行google,注意语言参数不能用下划线,时间戳需要传毫秒级时间戳
const date = new Date();
const formatter = new Intl.DateTimeFormat('de');
console.log(formatter.format(date));
// 11.5.2023
// 可以显示详细月份,避免歧义
const date = new Date();
const options = { year: 'numeric', month: 'long', day: 'numeric' };
const formatter = new Intl.DateTimeFormat('en-us',options);
console.log(formatter.format(date));
// May 11, 2023
// 直接格式化时间戳,需要传毫秒级时间戳
const formatter = new Intl.DateTimeFormat('en-us');
console.log(formatter.format(1683797308000));
// 5/11/2023
// 指定时区
const time=1683772108000;
const local='zh-cn';
const formatter = new Intl.DateTimeFormat(local,{ timeZone: "America/Denver" });
console.log("美国日期:",formatter.format(time));
const formatter2 = new Intl.DateTimeFormat(local,{ timeZone: "Asia/Shanghai" });
console.log("北京日期:",formatter2.format(time));
// 美国日期: 2023/5/10
// 北京日期: 2023/5/11
// 日期 + 时间 + 12小时制
const options = {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
hour12: true
};
const formatter = new Intl.DateTimeFormat('zh-cn',options);
console.log("日期+时间:",formatter.format(time));
// 日期+时间: 2023/5/11 上午10:28
// 日期 + 时间 + 24小时制
const options = {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
hour12: false
};
const formatter = new Intl.DateTimeFormat('zh-cn',options);
console.log("日期+时间:",formatter.format(time));
// 日期+时间: 2023/5/11 10:28
// 使用dayjs
const YmdHis = dayjs.tz(1683772108000, "Asia/Shanghai");
console.log(YmdHis.format('YYYY-MM-DD HH:mm:ss'));
// 2023-05-11 10:28:28
数字格式化
//只格式数字
const formatter = new Intl.NumberFormat('zh-CN');
console.log(formatter.format(1234567.89012));
// 1,234,567.89
//显示货币符号
const formatter = new Intl.NumberFormat('zh-CN', {
style: 'currency',
// 输出人民币
currency: 'CNY',
});
console.log(formatter.format(1234567.89012));
// ¥1,234,567.89
// 显示货币code
new Intl.NumberFormat('zh-CN',{ style: 'currency',currency: 'CNY',currencyDisplay: "code" }).format(1234567.890)
// CNY 1,234,567.89
// 换一个local参数,德国,币种保持不变
new Intl.NumberFormat('de',{ style: 'currency',currency: 'CNY',currencyDisplay: "code" }).format(1234567.890)
// 1.234.567,89 CNY