JavaScript toLocaleDateString() 方法
toLocaleDateString() 方法返回该日期对象日期部分的字符串,该字符串格式因不同语言而不同。新增的参数 locales 和 options 使程序能够指定使用哪种语言格式化规则,允许定制该方法的表现(behavior)。在旧版本浏览器中, locales 和 options 参数被忽略,使用的语言环境和返回的字符串格式是各自独立实现的。
定义和用法
toLocaleDateString() 方法可根据本地时间把 Date 对象的日期部分转换为字符串,并返回结果。
语法
dateObject.toLocaleDateString()
返回值
dateObject 的日期部分的字符串表示,以本地时间区表示,并根据本地规则格式化。
实例
<html><body><script type="text/javascript">var date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));// toLocaleDateString without arguments depends on the implementation,// the default locale, and the default time zonedate.toLocaleDateString();// → "12/11/2012" 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 month-day-year orderalert(date.toLocaleDateString("en-US"));// → "12/19/2012"// British English uses day-month-year orderalert(date.toLocaleDateString("en-GB"));// → "20/12/2012"// Korean uses year-month-day orderalert(date.toLocaleDateString("ko-KR"));// → "2012. 12. 20."// Arabic in most Arabic speaking countries uses real Arabic digitsalert(date.toLocaleDateString("ar-EG"));// → "٢٠/١٢/٢٠١٢"// for Japanese, applications may want to use the Japanese calendar,// where 2012 was the year 24 of the Heisei eraalert(date.toLocaleDateString("ja-JP-u-ca-japanese"));// → "24/12/20"// when requesting a language that may not be supported, such as// Balinese, include a fallback language, in this case Indonesianalert(date.toLocaleDateString(["ban", "id"]));// → "20/12/2012"</script></body></html>
性能
当格式化大量日期时,最好创建一个 Intl.DateTimeFormat 对象,然后使用该对象 format 属性提供的方法。