JavaScript Date toDateString() 方法
JavaScript 中的 Date.toDateString() 方法用于将日期对象转换为仅包含日期部分的字符串表示形式,而不包含时间信息。生成的字符串包含星期几、月份、日期和年份,但不包含时间和时区信息。
此方法不会更改原始 Date 对象;它仅返回其日期部分的字符串表示形式。如果提供的 Date 对象无效,则此方法返回"无效日期"。
语法
以下是 JavaScript Date toDateString() 方法的语法 -
toDateString();
此方法不接受任何参数。
返回值
此方法返回一个表示 Date 对象日期部分的字符串。
示例 1
在下面的程序中,我们将日期对象转换为仅表示日期部分的字符串 -
<html> <body> <script> const currentDate = new Date(); const dateString = currentDate.toDateString(); document.write(dateString); </script> </body> </html>
输出
执行后,我们可以看到一个表示日期部分的字符串。
示例 2
在这里,我们创建一个包含特定日期"2023-12-25"的日期对象,并使用 toDateString() 方法将其转换为字符串。
<html>
<body>
<script>
const specificDate = new Date("2023-12-25");
const dateString = specificDate.toDateString();
document.write(dateString);
</script>
</body>
</html>
输出
程序返回"Sun Dec 31 2023"作为输出。
示例 3
如果我们创建一个包含无效日期的日期对象,此方法将返回"无效日期"作为结果 -
<html>
<body>
<script>
const pastDate = new Date("2022-15-78");
const dateString = pastDate.toDateString();
document.write(dateString);
</script>
</body>
</html>
输出
上述程序没有包含范围内的月份和日期部分,因此返回"无效日期"作为输出。

