JavaScript toLocaleTimeString() 方法
The toLocaleTimeString() 方法返回该日期对象时间部分的字符串,该字符串格式因不同语言而不同。新增的参数 locales 和 options 使程序能够指定使用哪种语言格式化规则,允许定制该方法的表现(behavior)。在旧版本浏览器中, locales 和 options 参数被忽略,使用的语言环境和返回的字符串格式是各自独立实现的。
定义和用法
toLocaleTimeString() 方法可根据本地时间把 Date 对象的时间部分转换为字符串,并返回结果。
语法
dateObject.toLocaleTimeString()
返回值
dateObject 的时间部分的字符串表示,以本地时间区表示,并根据本地规则格式化。
实例
<html><body><script type="text/javascript">var date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));// toLocaleTimeString without arguments depends on the implementation,// the default locale, and the default time zonealert(date.toLocaleTimeString());// → "7:00:00 PM" if run in en-US locale with time zone America/Los_Angeles</script></body></html>
下例展示了本地化时间格式的一些变化。为了在应用的用户界面得到某种语言的时间格式,必须确保使用 locales 参数指定了该语言(可能还需要设置某些回退语言)。
<html><body><script type="text/javascript">var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));// formats below assume the local time zone of the locale;// America/Los_Angeles for the US// US English uses 12-hour time with AM/PMalert(date.toLocaleTimeString("en-US"));// → "7:00:00 PM"// British English uses 24-hour time without AM/PMalert(date.toLocaleTimeString("en-GB"));// → "03:00:00"// Korean uses 12-hour time with AM/PMalert(date.toLocaleTimeString("ko-KR"));// → "오후 12:00:00"// Arabic in most Arabic speaking countries uses real Arabic digitsalert(date.toLocaleTimeString("ar-EG"));// → "٧:٠٠:٠٠ م"// when requesting a language that may not be supported, such as// Balinese, include a fallback language, in this case Indonesianalert(date.toLocaleTimeString(["ban", "id"]));// → "11.00.00"</script></body></html>
性能
当格式化大量日期时,最好创建一个 Intl.DateTimeFormat 对象,然后使用该对象 format 属性提供的方法。