JavaScript Date toDateString() 方法



Date.toDateString() 方法用于在 JavaScript 中将日期对象转换为仅包含日期部分的字符串表示形式,不包含时间信息。生成的字符串包含星期几、月份、月份中的日期和年份,但不包含时间和时区信息。

此方法不会更改原始 Date 对象;它仅返回其日期组件的字符串表示形式。如果提供的 Date 对象无效,则此方法返回“Invalid 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

如果我们使用无效日期创建日期对象,则此方法返回“invalid date”作为结果:

<html>
<body>
<script>
   const pastDate = new Date("2022-15-78");
   const dateString = pastDate.toDateString();

   document.write(dateString);
</script>
</body>
</html>

输出

上述程序的月份和日期组件不在范围内,因此返回“invalid date”作为输出。

广告