JavaScript Date.toString() 方法用于将 Date 对象转换为字符串。返回值将是一个字符串,根据本地时区表示日期、时间和 timizone。
对于数字、布尔值和字符串等基元值,toString() 返回转换为字符串的基元值。如果 Date 对象为 “invalid”,则此方法返回 “invalid date” 作为结果。对于 null 和 undefined,toString() 分别返回 “null” 和 “undefined” 的字符串表示形式。
语法
以下是 JavaScript Date.toString() 方法的语法 -
toString();
此方法不接受任何参数。
返回值
此方法返回以字符串表示的日期和时间。
示例 1
在下面的示例中,我们将演示 JavaScript Date.toString() 方法的基本用法 -
<html>
<body>
<script>
const currentDate = new Date();
const dateString = currentDate.toString();
document.write(dateString);
</script>
</body>
</html>
输出
上面的程序以字符串形式返回 date 对象。
示例 2
在下面的示例中,我们为 date 对象提供了特定的日期和时间 (2023-12-26 06:30:00) -
<html>
<body>
<script>
const specificDate = new Date('2023-12-26 06:30:00');
const dateString = specificDate.toString();
document.write(dateString);
</script>
</body>
</html>
输出
它转换日期并将其作为字符串返回。
示例 3
在这里,日期对象是使用无效日期创建的,即超出有效范围的日期和时间值。
<html>
<body>
<script>
const specificDate = new Date('2023-15-56 06:30:00');
const dateString = specificDate.toString();
document.write(dateString);
</script>
</body>
</html>
输出
程序将返回 “invalid date” 作为结果。