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

浏览器兼容性

另见