在 JavaScript 中,Date.toDateString() 方法用于将日期对象转换为仅日期部分的字符串表示形式,而不包括时间信息。生成的字符串由星期几、月份、月份中的日期和年份组成,但不包括时间和时区信息。
此方法不会更改原始 Date 对象;它只返回其 Date 组件的 String 表示形式。如果提供的 Date 对象无效,则此方法返回 “Invalid Date”。
语法
以下是 JavaScript Date.toDateString() 方法的语法 -
toDateString();
此方法不接受任何参数。
返回值
此方法返回一个字符串,该字符串表示 Date 对象的日期部分。
示例 1
在下面的程序中,我们将 date 对象转换为仅表示 date 部分的字符串 -
<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
如果我们创建一个日期无效的 date 对象,此方法将返回 “invalid date” 作为结果 -
<html>
<body>
<script>
const pastDate = new Date("2022-15-78");
const dateString = pastDate.toDateString();
document.write(dateString);
</script>
</body>
</html>
输出
上述程序在该范围内没有 month 和 day 组件,这将返回 “invalid date” 作为输出。