formatting

Date.prototype.toJSON

Returns an ISO 8601 UTC string suitable for JSON serialization; called automatically by JSON.stringify when it encounters a Date. Equivalent to toISOString() for valid dates, but returns null for Invalid Dates instead of throwing.

date.toJSON()

Parameters

Parameter Purpose
() ignores its (optional) key argument
auto JSON.stringify calls this automatically
Invalid Date returns null

Examples

console.log(JSON.stringify({at: new Date('2026-07-19T00:00:00Z')})); // '{"at":"2026-07-19T00:00:00.000Z"}'

auto-serialization

console.log(new Date('2026-07-19').toJSON()); // '2026-07-19T00:00:00.000Z'

same as toISOString

console.log(new Date(NaN).toJSON()); // null

invalid -> null, not throw

Gotcha

JSON has no Date type, so the round-trip is one-way: JSON.parse gives back a string, not a Date. Rehydrate with new Date(str) in a reviver.

Related

← All JS Date methods · Math methods · Cron syntax