Intl.DateTimeFormat.prototype.format()

Intl.DateTimeFormat 实例的 format() 方法根据此 Intl.DateTimeFormat 对象的区域设置和格式选项来格式化日期。

¥The format() method of Intl.DateTimeFormat instances formats a date according to the locale and formatting options of this Intl.DateTimeFormat object.

Try it

语法

¥Syntax

js
format(date)

参数

¥Parameters

date

要格式化的日期。

返回值

¥Return value

表示给定 date 的字符串,根据该 Intl.DateTimeFormat 对象的区域设置和格式选项进行格式化。

¥A string representing the given date formatted according to the locale and formatting options of this Intl.DateTimeFormat object.

注意:大多数时候,format() 返回的格式是一致的。但是,即使在同一语言环境中,输出也可能因实现而异 - 输出变化是设计使然,并且规范允许。它也可能不是你所期望的。例如,字符串可以使用不间断空格或被双向控制字符包围。你不应该将 format() 的结果与硬编码常量进行比较。

¥Note: Most of the time, the formatting returned by format() is consistent. However, the output may vary between implementations, even within the same locale — output variations are by design and allowed by the specification. It may also not be what you expect. For example, the string may use non-breaking spaces or be surrounded by bidirectional control characters. You should not compare the results of format() to hardcoded constants.

示例

¥Examples

使用格式

¥Using format

使用 format getter 函数格式化单个日期,此处针对塞尔维亚:

¥Use the format getter function for formatting a single date, here for Serbia:

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."

使用映射格式

¥Using format with map

使用 format getter 函数格式化数组中的所有日期。请注意,该函数绑定到从中获取它的 Intl.DateTimeFormat,因此可以将其直接传递给 Array.prototype.map()

¥Use the format getter function for formatting all dates in an array. Note that the function is bound to the Intl.DateTimeFormat from which it was obtained, so it can be passed directly to 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"

规范

Specification
ECMAScript Internationalization API Specification
# sec-intl.datetimeformat.prototype.format

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看