此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

Date.prototype.toJSON()

基线 广泛可用

自 2015年7月 起,此特性已在主流浏览器中得到支持,可在大多数设备和浏览器版本中正常使用。

toJSON() 方法返回 Date 对象的字符串形式。

尝试一下

const event = new Date("August 19, 1975 23:15:30 UTC");

const jsonDate = event.toJSON();

console.log(jsonDate);
// Expected output: "1975-08-19T23:15:30.000Z"

console.log(new Date(jsonDate).toUTCString());
// Expected output: "Tue, 19 Aug 1975 23:15:30 GMT"

语法

js
toJSON()

描述

Date 实例引用一个具体的时间点。调用 toJSON() 返回一个 JSON 格式字符串(使用 toISOString()),表示该日期对象的值。默认情况下,这个方法常用于 JSON 序列化 Date 对象。

示例

使用 toJSON()

js
const jsonDate = new Date(0).toJSON(); // '1970-01-01T00:00:00.000Z'
const backToDate = new Date(jsonDate);

console.log(jsonDate); // 1970-01-01T00:00:00.000Z

规范

规范
ECMAScript® 2027 Language Specification
# sec-date.prototype.tojson

浏览器兼容性

参见