此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

Date.prototype.toLocaleTimeString()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2015年7月⁩.

toLocaleTimeString() 方法返回该日期对象时间部分的字符串,该字符串格式因语言而异。在支持 Intl.DateTimeFormat API 的实现中,该方法仅是调用了 Intl.DateTimeFormat 方法。

尝试一下

语法

参数

localesoptions 参数使程序能够指定使用哪种语言格式化规则,允许定制该方法的行为(behavior)。

在支持 Intl.DateTimeFormat API 的实现中,这些参数与构造函数的参数完全对应。而对于不支持 Intl.DateTimeFormat 的实现,则要求函数忽略这两个参数,使得函数使用的区域(locale)以及返回的字符串的格式完全取决于实现。

locales 可选

表示缩写语言代码(BCP 47 language tag)的字符串,或由此类字符串组成的数组。对应于 Intl.DateTimeFormat() 构造函数的 locales 参数。

在不支持 Intl.DateTimeFormat 的实现中,该参数会被忽略,并且通常会使用主机的区域设置。

options 可选

一个调整输出格式的对象。对应于 Intl.DateTimeFormat() 构造函数的 options 参数。如果其 dayPeriodhourminutesecondfractionalSecondDigits 属性全是 undefined,则 hourminutesecond 这三个属性会被设置为 "numeric"

在不支持 Intl.DateTimeFormat 的实现中,该参数会被忽略。

参见 Intl.DateTimeFormat() 构造函数以详细了解这些参数以及如何使用它们。

返回值

一个表示给定的 Date 实例的时间部分,且与语言相关的字符串。

在支持 Intl.DateTimeFormat 的实现中,该方法等价于 new Intl.DateTimeFormat(locales, options).format(date),其中的 options 已通过上述的规则进行规范化。

性能

当需要格式化大量的日期(date)时,最好创建一个 Intl.DateTimeFormat 对象,并使用其 format() 方法。

示例

使用 toLocaleTimeString()

没有指定 locale 时,返回一个使用默认语言环境和格式设置(options)的格式化字符串。

使用 locales

以下示例显示不同的本地化时间格式。为了获得用户界面(UI)使用的语言格式表示的字符串,请确保使用了 locales 参数,并将其指定为用户所使用的语言。

使用 options

可以使用 options 参数自定义 toLocaleTimeString() 所提供的结果。

规范

Specification
ECMAScript® 2026 Language Specification
# sec-date.prototype.tolocaletimestring
ECMAScript® 2026 Internationalization API Specification
# sup-date.prototype.tolocaletimestring

浏览器兼容性

参见