Date.prototype.toJSON()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

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() の呼び出しは、Date オブジェクトの値を表す文字列 (toISOString() を使用) を返します。このメソッドは、既定で、 Date オブジェクトを JSON シリアライズ中に有益にシリアライズし、その後、 Date() コンストラクター または Date.parse() の更新版としての JSON.parse() を使用してデシリアライズできるようにすることが一般に意図されています。

toJSON() を使う

js
const jsonDate = new Date().toJSON();
const backToDate = new Date(jsonDate);

console.log(jsonDate); // 2015-10-26T07:46:36.611Z

シリアライズの往復

日付文字列を含む JSON を解釈する場合、 Date.parse() を使用して、元の日付オブジェクトに復活させることができます。

js
const fileData = {
  author: "John",
  title: "Date.prototype.toJSON()",
  createdAt: new Date(2019, 3, 15),
  updatedAt: new Date(2020, 6, 26),
};
const response = JSON.stringify(fileData);

// ネットワーク経由での送信をイメージ

const data = JSON.parse(response, (key, value) => {
  if (key === "createdAt" || key === "updatedAt") {
    return Date.parse(value);
  }
  return value;
});

console.log(data);

仕様書

Specification
ECMAScript® 2025 Language Specification
# sec-date.prototype.tojson

ブラウザーの互換性

BCD tables only load in the browser

関連情報