intl
这个模块提供了日期和数字格式化方法和支持工具。格式化函数formatDate()、formatNumber()和substitute()依赖于所有web浏览器中可用的国际化api,以启用对语言环境敏感的日期、时间和数字格式化。
数字格式化属性
可以使用formatNumber()将数字格式化为三种不同的样式:小数、百分数或货币。
const decimalFormatted = intl.formatNumber(12.5, {
style: "decimal"
});
const percentFormatted = intl.formatNumber(12.5, {
style: "percent"
});
const currencyFormatted = intl.formatNumber(12.5, {
style: "currency",
currency: "EUR",
currencyDisplay: "symbol"
});
console.log(decimalFormatted); // 12,5
console.log(percentFormatted); // 1 250 %
console.log(currencyFormatted); // 12,50 €
默认情况下,使用指定样式的适当选项集对数字进行格式化。还可以控制是否使用具有整数、小数数或有效数字的分组分隔符。
日期和时间格式
可以使用formatDate()格式化日期。可以控制格式化日期的每个日期-时间组件:工作日、era、年、月、日、小时、分钟、秒和timeZoneName。为了确定每个组件的最合适顺序,或者是使用24小时还是12小时的时间格式,要考虑语言环境和区域。例如,用en-US和en-GB格式化日期会得到不同的结果。
const now = Date.now();
const dateTimeFormatOptions = {
weekday: "long",
day: "2-digit",
month: "long",
year: "numeric",
hour: "numeric",
minute: "numeric"
});
const formatted = intl.formatDate(now, dateTimeFormatOptions);
console.log(formatted);
提示和技巧
formatDate()、formatNumber()和substitute()函数是对缓存所创建的Intl的Intl api的轻量级包装器。Intl.DateTimeFormat , Intl.NumberFormat一组选项的格式化程序对象。考虑重用相同的options“对象,以避免重新创建这些对象。
const currencyFormatter = {
style: "currency",
currency: "EUR",
currencyDisplay: "symbol"
};
function formatCurrency(amount) {
return formatNumber(amount, currencyFormatter);
}
方法预览
convertDateFormatToIntlOptions():将web地图日期格式字符串转换为Intl。DateTimeFormat选择对象。
convertNumberFormatToIntlOptions():将一个数字格式转换为一个Intl。NumberFormatOptions对象。
formatDate():将日期或数字值格式化为当前语言环境中的字符串。
formatNumber():将数字值格式化为当前语言环境中的字符串。
getLocale():返回API使用的当前环境字符串。
onLocaleChange():当语言环境发生变化时,这个回调函数来通知。
prefersRTL():为输入区域设置提供从右到左的首选项。
setLocale():设置API使用的语言环境。
substitute():使用它来用参数数据中的值替换模板字符串中的键。
版权声明:
作者:Gomo
链接:https://www.develophm.com/index.php/intl/610/
来源:开发之家
文章版权归作者所有,未经允许请勿转载。
共有 0 条评论