JavaScript toLocaleTimeString() 方法

The toLocaleTimeString() 方法返回该日期对象时间部分的字符串,该字符串格式因不同语言而不同。新增的参数 locales 和 options 使程序能够指定使用哪种语言格式化规则,允许定制该方法的表现(behavior)。在旧版本浏览器中, locales 和 options 参数被忽略,使用的语言环境和返回的字符串格式是各自独立实现的。


定义和用法

toLocaleTimeString() 方法可根据本地时间把 Date 对象的时间部分转换为字符串,并返回结果。

语法
  1. dateObject.toLocaleTimeString()
返回值

dateObject 的时间部分的字符串表示,以本地时间区表示,并根据本地规则格式化。


实例

  1. <html>
  2. <body>
  3. <script type="text/javascript">
  4. var date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));
  5. // toLocaleTimeString without arguments depends on the implementation,
  6. // the default locale, and the default time zone
  7. alert(date.toLocaleTimeString());
  8. // → "7:00:00 PM" if run in en-US locale with time zone America/Los_Angeles
  9. </script>
  10. </body>
  11. </html>

下例展示了本地化时间格式的一些变化。为了在应用的用户界面得到某种语言的时间格式,必须确保使用 locales 参数指定了该语言(可能还需要设置某些回退语言)。

  1. <html>
  2. <body>
  3. <script type="text/javascript">
  4. var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
  5. // formats below assume the local time zone of the locale;
  6. // America/Los_Angeles for the US
  7. // US English uses 12-hour time with AM/PM
  8. alert(date.toLocaleTimeString("en-US"));
  9. // → "7:00:00 PM"
  10. // British English uses 24-hour time without AM/PM
  11. alert(date.toLocaleTimeString("en-GB"));
  12. // → "03:00:00"
  13. // Korean uses 12-hour time with AM/PM
  14. alert(date.toLocaleTimeString("ko-KR"));
  15. // → "오후 12:00:00"
  16. // Arabic in most Arabic speaking countries uses real Arabic digits
  17. alert(date.toLocaleTimeString("ar-EG"));
  18. // → "٧:٠٠:٠٠ م"
  19. // when requesting a language that may not be supported, such as
  20. // Balinese, include a fallback language, in this case Indonesian
  21. alert(date.toLocaleTimeString(["ban", "id"]));
  22. // → "11.00.00"
  23. </script>
  24. </body>
  25. </html>

性能

当格式化大量日期时,最好创建一个 Intl.DateTimeFormat 对象,然后使用该对象 format 属性提供的方法。

分类导航