跳至主要内容

[WebAPIs] Intl API

keywords: Intl, Intl.ListFormat, Intl.DateTimeFormat, Intl.NumberFormat

Intl.NumberFormat

// Intl.NumberFormat
new Intl.NumberFormat('en').format(1000); // 1,000

Intl.DateTimeFormat

Intl.DateTimeFormat

// Intl.DataTimeFormat
function ISOtoLongDate(isoString, locale = 'en-US') {
const options = { month: 'long', day: 'numeric', year: 'numeric' };
const date = new Date(isoString);
const longDate = new Intl.DateTimeFormat(locale, options).format(date);
return longDate;
}

Intl.DisplsyName

type Locales = string | string[];
type Options = {
type: "language" | "region" | "script" | "currency" | "calendar" | "dateTimeField",
localeMatcher: "lookup" | "best fit", // default "best fit"
style: "narrow" | "short" | "long", // default "long"
languageDisplay: "dialect" | "standard", // default "dialect"
fallback: "code" | "none", // default "none"
}

new Intl.DisplayNames(locales: Locales, options: Options);
  • locales 可以是帶有 fallback 功能的 Array(i.e., ['zh-Hant', 'en-US'])或單一字串('zh-Hant'
  • options.type:包含 calendarcurrecnydateTimeFieldlanguageregionscript
warning

有些 type 的項目(例如,calendardateTimeField)目前只有瀏覽器有實作,在 server 使用是須留意相容性或需透過 Babel 處理。

可以將 region code、language、script、currency 轉成特定語系下的文字來顯示:

/** 根據 Region Code 取得該語言下顯示的「地區名稱」 */
const regionNames = new Intl.DisplayNames(['zh-Hant'], {
type: 'region',
});
regionNames.of('TW'); // 台灣
regionNames.of('US'); // 美國

/** 根據 language-script-region 取得該語言下顯示的「語言名稱」 */
const languageNames = new Intl.DisplayNames(['zh-Hant'], {
type: 'language',
});
languageNames.of('zh-Hant'); // 繁體中文
languageNames.of('zh-TW'); // 中文(台灣)

/** 根據 script code 取得該語言下顯示的「script 名稱」 */
const scriptNames = new Intl.DisplayNames(['zh-Hant'], {
type: 'script',
});
scriptNames.of('Hant'); // 繁體
scriptNames.of('Hans'); // 簡體
scriptNames.of('Latn'); // 拉丁文

/** 根據 currency 取得該語言下顯示的「幣別名稱」 */
const currencyNames = new Intl.DisplayNames(['zh-Hant'], {
type: 'currency',
});
currencyNames.of('TWD'); // 新台幣
currencyNames.of('KRW'); // 韓元
currencyNames.of('JPY'); // 日圓

/** 根據 date time field 取得該語言下顯示的「幣別名稱」 */
const dateTimeFieldNames = new Intl.DisplayNames('zh-Hant', {
type: 'dateTimeField',
});
dateTimeFieldNames.of('year'); // 年
dateTimeFieldNames.of('weekOfYear'); // 週