JavaScript toLocaleDateString() 方法

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


定义和用法

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

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

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


实例

  1. <html>
  2. <body>
  3. <script type="text/javascript">
  4. var date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));
  5. // toLocaleDateString without arguments depends on the implementation,
  6. // the default locale, and the default time zone
  7. date.toLocaleDateString();
  8. // → "12/11/2012" 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 month-day-year order
  8. alert(date.toLocaleDateString("en-US"));
  9. // → "12/19/2012"
  10. // British English uses day-month-year order
  11. alert(date.toLocaleDateString("en-GB"));
  12. // → "20/12/2012"
  13. // Korean uses year-month-day order
  14. alert(date.toLocaleDateString("ko-KR"));
  15. // → "2012. 12. 20."
  16. // Arabic in most Arabic speaking countries uses real Arabic digits
  17. alert(date.toLocaleDateString("ar-EG"));
  18. // → "٢٠‏/١٢‏/٢٠١٢"
  19. // for Japanese, applications may want to use the Japanese calendar,
  20. // where 2012 was the year 24 of the Heisei era
  21. alert(date.toLocaleDateString("ja-JP-u-ca-japanese"));
  22. // → "24/12/20"
  23. // when requesting a language that may not be supported, such as
  24. // Balinese, include a fallback language, in this case Indonesian
  25. alert(date.toLocaleDateString(["ban", "id"]));
  26. // → "20/12/2012"
  27. </script>
  28. </body>
  29. </html>

性能

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

分类导航