JavaScript Date toLocaleString() 方法
JavaScript 中的 Date.toLocaleString() 方法用于将 Date 对象转换为字符串,该字符串基于当前语言环境设置,以特定于语言环境的格式表示日期和时间。
语法
以下是 JavaScript Date toLocaleString() 方法的语法 -
toLocaleString(locales, options);
参数
此方法接受两个参数。具体说明如下 -
- locales (可选) - 表示 BCP 47 语言标签的字符串或字符串数组,或此类字符串的数组。它指定用于日期格式的一个或多个语言环境。如果 locales 参数未定义或为空数组,则使用运行时的默认语言环境。
- options (可选) − 一个允许您自定义格式的对象。它可以包含诸如星期、年、月、日、小时、分钟、秒等属性,具体取决于您格式化的是日期还是时间。
返回值
此方法使用语言环境设置以字符串形式返回 Date 对象。
示例 1
在下面的示例中,我们将演示 JavaScript Date toLocaleString() 方法的基本用法 −
<html> <body> <script> const currentDate = new Date(); const formattedDate = currentDate.toLocaleString(); document.write(formattedDate); </script> </body> </html>
输出
它使用语言环境设置返回一个字符串形式的 Date 对象。
示例 2
在这里,我们使用带有特定选项的 toLocaleString() 方法,根据英语(美国)语言环境中的长星期、年、月、日格式来格式化日期。
<html>
<body>
<script>
const currentDate = new Date();
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
const formattedDate = currentDate.toLocaleString('en-US', options);
document.write(formattedDate);
</script>
</body>
</html>
输出
正如我们在输出中看到的,它根据指定的格式显示日期。
示例 3
在此示例中,我们自定义时间格式,以 12 小时制显示小时、分钟和秒,并为个位数添加前导零。
<html>
<body>
<script>
const currentDate = new Date();
const options = { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true };
const formattedDate = currentDate.toLocaleString('en-US', options);
document.write(formattedDate);
</script>
</body>
</html>
输出
正如我们在输出中看到的,它以 12 小时制显示日期。

