Intl.DateTimeFormat.prototype.format()
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"
语法
format(date)
参数
日期
-
要格式化的日期。可以是
Date
或Temporal.PlainDateTime
对象。此外,如果DateTimeFormat
对象被配置为打印日期的至少一个相关部分,它还可以是Temporal.PlainTime
、Temporal.PlainDate
、Temporal.PlainYearMonth
或Temporal.PlainMonthDay
对象。注意:
Temporal.ZonedDateTime
对象总是会抛出TypeError
;请使用Temporal.ZonedDateTime.prototype.toLocaleString()
或将其转换为Temporal.PlainDateTime
对象。省略此参数会格式化当前日期(由
Date.now()
返回),这可能会有些令人困惑,因此建议始终显式传递日期。
返回值
一个字符串,表示根据该 Intl.DateTimeFormat
对象的区域设置和格式化选项格式化后的给定 date
。
注意: 大多数情况下,format()
返回的格式是一致的。然而,输出可能因实现而异,即使在同一区域设置下也是如此 — 输出差异是故意的,并且规范允许。它也可能不是您期望的。例如,字符串可能使用不间断空格,或者被双向控制字符包围。您不应将 format()
的结果与硬编码的常量进行比较。
示例
使用格式
使用 format
getter 函数格式化单个日期,这里以塞尔维亚为例
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()
。
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 |
浏览器兼容性
加载中…