Intl.DateTimeFormat.prototype.formatToParts()

Baseline 已廣泛支援

此特性已成熟穩定,適用於多種裝置和瀏覽器版本。自 2018 年 10 月起,它已在各瀏覽器中可用。

formatToParts() 方法是 Intl.DateTimeFormat 例項的一個方法,它返回一個物件陣列,表示透過 format() 方法格式化後的字串的每個部分。這對於構建由區域設定特定的標記組成的自定義字串非常有用。

試一試

const date = new Date(2012, 5);
const options = {
  weekday: "long",
  year: "numeric",
  month: "long",
  day: "numeric",
};
const dateTimeFormat = new Intl.DateTimeFormat("en-US", options);

const parts = dateTimeFormat.formatToParts(date);
const partValues = parts.map((p) => p.value);

console.log(partValues);
// Expected output: "["Friday", ", ", "June", " ", "1", ", ", "2012"]"

語法

js
formatToParts(date)

引數

date 可選

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

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

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

返回值

一個包含格式化日期部分的 Array。每個物件都有兩個屬性:typevalue,都包含一個字串。按提供的順序連線 value 字串將得到與 format() 相同的字串。type 可以是 日期時間元件 之一。

weekday

例如 "M""Monday""Montag"

era

例如 "BC""AD"

例如 "2012""96"

月份

例如 "12""January"

例如 "17"

dayPeriod

例如 "AM""PM""in the morning""noon"

小時

例如 "3""03"

minute

例如 "00"

例如 "07""42"

fractionalSecond

例如 "0""00""000"

timeZoneName

例如 "UTC""CET""Central European Time"

type 還可以是以下之一:

literal

格式模式中的任何字串,並且不受 date 影響;例如 "/"", ""o'clock""de"" " 等。

relatedYear

一個 4 位數的公曆年份,以防日曆的表示是 yearName 而不是年份;例如 "2019"。有關更多詳細資訊,請參閱 命名年份

yearName

賦予年份的名稱,通常在沒有連續年份概念的日曆中;例如 "geng-zi"

unknown

保留給任何未被識別為以上任何一種的標記;這種情況應很少見。

示例

使用 formatToParts()

format() 方法輸出本地化的、不透明的字串,無法直接操作。

js
const date = Date.UTC(2012, 11, 17, 3, 0, 42);

const formatter = new Intl.DateTimeFormat("en-us", {
  weekday: "long",
  year: "numeric",
  month: "numeric",
  day: "numeric",
  hour: "numeric",
  minute: "numeric",
  second: "numeric",
  fractionalSecondDigits: 3,
  hour12: true,
  timeZone: "UTC",
});

formatter.format(date);
// "Monday, 12/17/2012, 3:00:42.000 AM"

然而,在許多使用者介面中,您可能希望自定義此字串的格式,或將其與其他文字交錯。formatToParts() 方法以部分形式提供相同的資訊。

js
formatter.formatToParts(date);

// return value:
[
  { type: "weekday", value: "Monday" },
  { type: "literal", value: ", " },
  { type: "month", value: "12" },
  { type: "literal", value: "/" },
  { type: "day", value: "17" },
  { type: "literal", value: "/" },
  { type: "year", value: "2012" },
  { type: "literal", value: ", " },
  { type: "hour", value: "3" },
  { type: "literal", value: ":" },
  { type: "minute", value: "00" },
  { type: "literal", value: ":" },
  { type: "second", value: "42" },
  { type: "fractionalSecond", value: "000" },
  { type: "literal", value: " " },
  { type: "dayPeriod", value: "AM" },
];

現在資訊可以單獨獲取,並可以以自定義方式重新格式化和連線。例如,可以使用 Array.prototype.map()箭頭函式switch 語句模板字面量Array.prototype.join(),為特定元件插入額外的標記。

js
const dateString = formatter
  .formatToParts(date)
  .map(({ type, value }) => {
    switch (type) {
      case "dayPeriod":
        return `<em>${value}</em>`;
      default:
        return value;
    }
  })
  .join("");

console.log(dateString);
// "Monday, 12/17/2012, 3:00:42.000 <em>AM</em>"

命名年份

有些日曆使用命名年份;例如,中國和藏曆使用 60 年的 六十甲子 命名年份週期。這些日曆沒有通用的方法來明確地編號每一年的年份,因此年份是透過與公曆中對應的年份相關聯來區分的。在這種情況下,當 DateTimeFormat 配置為輸出年份元件時,會輸出一個 relatedYear 標記而不是 year

js
const df = new Intl.DateTimeFormat("zh-u-ca-chinese");
df.formatToParts(Date.UTC(2012, 11, 17, 3, 0, 42));

// return value:
[
  { type: "relatedYear", value: "2012" },
  { type: "literal", value: "年" },
  { type: "month", value: "十一月" },
  { type: "day", value: "4" },
];

有時,日期時間元件選項的組合會對映到也包含 yearName 的格式。沒有單獨的選項可以控制是否顯示 yearName。例如,以下選項將 month 設定為 "long",並導致出現 yearName 標記,儘管 year 仍然是 "numeric"

js
const opts = { year: "numeric", month: "long", day: "numeric" };
const df = new Intl.DateTimeFormat("zh-u-ca-chinese", opts);
df.formatToParts(Date.UTC(2012, 11, 17, 3, 0, 42));

// return value:
[
  { type: "relatedYear", value: "2012" },
  { type: "yearName", value: "壬辰" },
  { type: "literal", value: "年" },
  { type: "month", value: "十一月" },
  { type: "day", value: "4" },
];

由於 format() 只是將所有 value 字串連線在一起,因此在這種情況下,您將在輸出中同時看到公曆年份和年份名稱。

規範

規範
ECMAScript® 2026 國際化 API 規範
# sec-Intl.DateTimeFormat.prototype.formatToParts

瀏覽器相容性

另見