JavaScript Date.toJSON() 方法用于根据世界时将 Date 对象转换为表示给定日期的字符串,格式为日期时间 JSON 字符串格式。如果 Date 对象为 Invalid Date,则此方法返回 “null” 作为结果。此外,此方法不接受任何参数。
语法
以下是 JavaScript Date.toJSON() 方法的语法 -
toJSON();
此方法不接受任何参数。
返回值
一个字符串,根据世界时以日期时间字符串格式表示给定日期。
示例 1
在以下示例中,我们使用 JavaScript Date.toJSON() 方法将当前日期和时间转换为 JSON 格式的字符串。
<html>
<body>
<script>
const currentDate = new Date();
const jsonDate = currentDate.toJSON();
document.write(jsonDate);
</script>
</body>
</html>
输出
正如我们所看到的,此方法返回一个格式化的 JSON 字符串。
示例 2
在这里,我们正在创建一个具有特定日期和时间“2023-12-31T08:15:30”的日期对象 -
<html>
<body>
<script>
const customDate = new Date('2023-12-31T08:15:30');
const jsonCustomDate = customDate.toJSON();
document.write(jsonCustomDate);
</script>
</body>
</html>
输出
该程序将特定日期和时间转换为格式化的 JSON 字符串。
示例 3
在这里,我们提供的日期值为 “50”,这超出了范围。
<html>
<body>
<script>
const currentDate = new Date('2023-12-50T05:06:01.516Z');
const jsonDate = currentDate.toJSON();
document.write(jsonDate);
</script>
</body>
</html>
输出
如果我们执行程序,则 “null” 将作为输出返回。
示例 4
在以下示例中,我们将向日期对象添加 10 天,并将修改后的日期转换为 JSON 格式的字符串。
<html>
<body>
<script>
const futureDate = new Date();
futureDate.setDate(futureDate.getDate() + 10);
const jsonFutureDate = futureDate.toJSON();
document.write(jsonFutureDate);
</script>
</body>
</html>
输出
结果将是一个字符串,表示未来 10 天的日期和时间。