Intl.DurationFormat 现已成为 Baseline Newly available

发布时间:2025 年 3 月 20 日

您可能在网页上看到的常见信息是一段文本,说明距离某个事件还有多久,或者自某个事件发生以来已经过了多长时间。这通常表示为一个字符串,用于传达以小时、分钟、秒或其他有用的时间单位表示的持续时间。

Intl.DurationFormat 是一个有用的功能,可以在浏览器中为您执行此操作,同时考虑到您可能有的任何国际化需求,而无需额外的 JavaScript。截至 2025 年 3 月,它已成为 Baseline Newly available。

Intl.DurationFormat 的工作原理

Intl.DurationFormat 是一个类,实例化后,它会返回一个描述持续时间的字符串。它的工作原理是指定一个对象,其中包含与您要为其生成字符串的时间单位相对应的键和值

// Specify the duration:
const duration = {
  years: 1,
  hours: 20,
  minutes: 15,
  seconds: 35
};

// Output: '1 yr, 20 hr, 15 min, 35 sec'
new Intl.DurationFormat('en').format(duration);

要以长格式返回字符串,请将 'long' 值传递给构造函数第二个参数中的 style 选项

const duration = {
  years: 1,
  hours: 20,
  minutes: 15,
  seconds: 35
};

// Output: '1 year, 20 hours, 15 minutes, 35 seconds'
new Intl.DurationFormat('en', { style: 'long' }).format(duration);

到目前为止,这些示例生成的是英语字符串。鉴于这是一项国际化功能,它的真正用处在于您可以传入任何有效的语言区域设置,并获得以您需要的任何受支持语言格式化的字符串

const duration = {
  years: 1,
  hours: 20,
  minutes: 15,
  seconds: 35
};

// Output: '1 Jahr, 20 Stunden, 15 Minuten und 35 Sekunden'
new Intl.DurationFormat('de', { style: 'long' }).format(duration);

// Output: '1 año, 20 horas, 15 minutos y 35 segundos'
new Intl.DurationFormat('es', { style: 'long' }).format(duration);

// Output: '1年20小时15分钟35秒钟'
new Intl.DurationFormat('zh', { style: 'long' }).format(duration);

// Output: '1 år, 20 timer, 15 minutter og 35 sekunder'
new Intl.DurationFormat('no', { style: 'long' }).format(duration);

// Output: 'mwaka 1, saa 20, dakika 15 na sekunde 35'
new Intl.DurationFormat('sw', { style: 'long' }).format(duration);

这些示例仅触及了您可以使用这项新功能执行的操作。要更深入地了解它的功能,请阅读 MDN 上的 Intl.DurationFormat 文档 以获取更多信息。