JavaScript 中的 Date.toLocaleString() 方法用于将 Date 对象转换为字符串,根据当前的区域设置,以特定于区域设置的格式表示日期和时间。
语法
以下是 JavaScript Date.toLocaleString() 方法的语法 -
toLocaleString(locales, options);
参数
此方法接受两个参数。下面描述相同 -
- locales (可选) - 表示 BCP 47 语言标签的字符串或字符串数组,或此类字符串的数组。它为日期格式指定一个或多个区域设置。如果 locales 参数未定义或为空数组,则使用运行时的默认区域设置。
- options (可选) − 允许您自定义格式的对象。它可以具有 weekday、year、month、day、hour、minute、second 等属性,具体取决于您是格式化日期还是时间。
返回值
此方法使用 locale 设置将 Date 对象作为字符串返回。
示例 1
在下面的示例中,我们将演示 JavaScript Date.toLocaleString()方法的基本用法 -
<html>
<body>
<script>
const currentDate = new Date();
const formattedDate = currentDate.toLocaleString();
document.write(formattedDate);
</script>
</body>
</html>
输出
它使用 locale 设置以字符串形式返回 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 小时制格式显示日期。