在 JavaScript 中,Date.toLocaleDateString() 方法用于将日期对象转换为字符串,根据当前区域设置格式表示日期的日期部分。
toLocaleDateString() 方法根据特定于区域设置的约定和格式选项返回一个字符串,该字符串表示给定 Date 对象的日期部分。返回的字符串的格式可能因区域设置和提供的选项而异。
语法
以下是 JavaScript Date.toLocaleDateString()方法的语法 -
toLocaleDateString(locales, options);
参数
此方法接受两个参数。相同的描述如下 -
- locales (可选) - 表示 BCP 47 语言标签的字符串或字符串数组,或此类字符串的数组。它为日期格式指定一个或多个区域设置。如果 locales 参数未定义或为空数组,则使用运行时的默认区域设置。
- options(可选)− 包含用于自定义日期格式的属性的对象。此对象可以具有 'weekday'、'year'、'month'、'day' 等属性。每个属性都可以具有 'numeric'、'2-digit'、'long'、'short' 或 'narrow' 等值,以自定义日期该部分的显示。
返回值
此方法使用区域设置约定,仅返回日期对象的日期(而不是时间)作为字符串。
示例 1
在下面的示例中,我们将演示 JavaScript Date.toLocaleDateString()方法的基本用法 -
<html>
<body>
<script>
const today = new Date();
const dateString = today.toLocaleDateString();
document.write(dateString);
</script>
</body>
</html>
输出
上面的程序使用 locale 约定将 date 对象的日期作为字符串返回。
示例 2
在此示例中,我们使用 “options” 参数指定长格式日期格式,包括工作日、月、日和年。我们还将区域设置设置为“en-US” -
<html>
<body>
<script>
const today = new Date();
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
const dateString = today.toLocaleDateString('en-US', options);
document.write(dateString);
</script>
</body>
</html>
输出
正如我们在输出中看到的那样,它显示长格式的日期格式。
示例 3
在这里,我们通过将指定的 locale 字符串作为第一个参数传递给 toLocaleDateString() 方法来使用不同的 locale -
<html>
<body>
<script>
const today = new Date();
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
document.write(today.toLocaleDateString('en-US', options), "");
document.write(today.toLocaleDateString('fr-FR', options));
</script>
</body>
</html>
输出
上述程序返回 “US English” 和 “Standard French” 的日期字符串。