Intl.DateTimeFormat.prototype.format()

Baseline 已廣泛支援

此功能已成熟,可跨多種裝置和瀏覽器版本使用。自 2017 年 9 月以來,它已在瀏覽器中提供。

format() 方法用於 Intl.DateTimeFormat 例項,根據該 Intl.DateTimeFormat 物件的區域設定和格式化選項來格式化日期。

試一試

const options = {
  weekday: "long",
  year: "numeric",
  month: "long",
  day: "numeric",
};
const date = new Date(2012, 5);

const dateTimeFormat1 = new Intl.DateTimeFormat("sr-RS", options);
console.log(dateTimeFormat1.format(date));
// Expected output: "петак, 1. јун 2012."

const dateTimeFormat2 = new Intl.DateTimeFormat("en-GB", options);
console.log(dateTimeFormat2.format(date));
// Expected output: "Friday, 1 June 2012"

const dateTimeFormat3 = new Intl.DateTimeFormat("en-US", options);
console.log(dateTimeFormat3.format(date));
// Expected output: "Friday, June 1, 2012"

語法

js
format(date)

引數

日期

要格式化的日期。可以是 DateTemporal.PlainDateTime 物件。此外,如果 DateTimeFormat 物件被配置為列印日期的至少一個相關部分,它還可以是 Temporal.PlainTimeTemporal.PlainDateTemporal.PlainYearMonthTemporal.PlainMonthDay 物件。

注意: Temporal.ZonedDateTime 物件總是會丟擲 TypeError;請使用 Temporal.ZonedDateTime.prototype.toLocaleString() 或將其轉換為 Temporal.PlainDateTime 物件。

省略此引數會格式化當前日期(由 Date.now() 返回),這可能會有些令人困惑,因此建議始終顯式傳遞日期。

返回值

一個字串,表示根據該 Intl.DateTimeFormat 物件的區域設定和格式化選項格式化後的給定 date

注意: 大多數情況下,format() 返回的格式是一致的。然而,輸出可能因實現而異,即使在同一區域設定下也是如此 — 輸出差異是故意的,並且規範允許。它也可能不是您期望的。例如,字串可能使用不間斷空格,或者被雙向控制字元包圍。您不應將 format() 的結果與硬編碼的常量進行比較。

示例

使用格式

使用 format getter 函式格式化單個日期,這裡以塞爾維亞為例

js
const options = {
  weekday: "long",
  year: "numeric",
  month: "long",
  day: "numeric",
};
const dateTimeFormat = new Intl.DateTimeFormat("sr-RS", options);
console.log(dateTimeFormat.format(new Date()));
// "недеља, 7. април 2013."

將 format 與 map 一起使用

使用 format getter 函式格式化陣列中的所有日期。請注意,該函式已繫結到其所獲得的 Intl.DateTimeFormat 物件,因此可以直接傳遞給 Array.prototype.map()

js
const a = [new Date(2012, 8), new Date(2012, 11), new Date(2012, 3)];
const options = { year: "numeric", month: "long" };
const dateTimeFormat = new Intl.DateTimeFormat("pt-BR", options);
const formatted = a.map(dateTimeFormat.format);
console.log(formatted.join("; "));
// "setembro de 2012; dezembro de 2012; abril de 2012"

規範

規範
ECMAScript® 2026 國際化 API 規範
# sec-intl.datetimeformat.prototype.format

瀏覽器相容性

另見