使用 Intl.DurationFormat 进行本地化持续时间

Hire Me! I'm currently looking for my next role in developer relations and advocacy. If you've got an open role and think I'd be a fit, please reach out. You can also find me on LinkedIn.

雇用我! 我目前正在寻找下一个开发者关系和倡导的角色。如果您有一个空缺的职位并认为我适合,请 联系我。您还可以在 LinkedIn 上找到我。

Last year I had the opportunity to give a talk on the web platform's Intl specification. This made me incredibly happy because in preparing for the presentation, I discovered so many cool features and capabilities of the spec that I had no idea existed. Almost a year ago, I wrote up a blog post on Intl.RelativeTimeFormat, talking about how the API was easy to use, but perhaps a bit difficult when dealing when determining the best values to use when formatting dynamic dates. Today, I'm going to turn my attention to a related spec, Intl.DurationFormat

去年我有机会在网络平台的 Intl 规范上做一个演讲。这让我非常高兴,因为在准备演讲时,我发现了许多我之前不知道的规范的酷功能和能力。差不多一年前,我写了一篇关于 Intl.RelativeTimeFormat 的博客文章,谈到这个 API 易于使用,但在处理动态日期格式化时确定最佳值可能有点困难。今天,我将把注意力转向一个相关的规范,Intl.DurationFormat

The Basics

基础知识

The DurationFormat API works like so:

DurationFormat API 的工作方式如下:

  • Given a locale (defaulting to the browser's locale)
  • 给定一个区域设置(默认为浏览器的区域设置)
  • Given a set of values representing time in different units (days, hours, etc)
  • 给定一组表示不同单位(天、小时等)时间的值
  • Given a 'style' (long, short, narrow, and digital)
  • 给定一个 'style'(长、短、窄和数字)
  • Report the duration in the desired locale
  • 以所需的语言环境报告持续时间

So for example, you can define a duration like so:

例如,您可以这样定义持续时间:

let duration = { days: 1, hours: 5, minutes: 32
}

I can then create a localized string for the duration like so:

然后我可以这样创建一个本地化的持续时间字符串:

let durationFormatter = new Intl.DurationFormat(navigator.language, { style: 'long' }); dur = durationFormatter.format(duration);

Which reports: 1 day, 5 hours, 32 minutes. Changing the locale to fr gives 1 jour, 5 heures et 32 minutes. That's with the long style, in short form you get 1 day, 5 hr, 32 min and 1 j, 5 h et 32 min. The narrow form is shorter while digital looks more like a digital clock and is better for durations less than a day. For ex...

开通本站会员,查看完整译文。

Home - Wiki
Copyright © 2011-2025 iteam. Current version is 2.142.0. UTC+08:00, 2025-02-22 05:05
浙ICP备14020137号-1 $Map of visitor$