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
Date.prototype.toISOString
Returns the date as an ISO 8601 extended-format string in UTC, always ending in 'Z'. This is the canonical machine-readable serialization and the format most APIs and databases accept.
Date.prototype.getTime
Returns the underlying timestamp of the date as milliseconds since the Unix epoch (1970-01-01T00:00:00Z). This is the canonical way to compare, subtract, or serialize a Date as a number.
Date.parse
Parses a date string and returns the corresponding milliseconds since the Unix epoch, or NaN if unrecognized. Only the ISO 8601 subset is guaranteed portable; any other format is implementation-defined.
Date.prototype.toLocaleDateString
Returns the date portion formatted for a given locale and options, without the time. For repeated formatting, cache an Intl.DateTimeFormat instead - it is significantly faster.
Date.prototype.toLocaleTimeString
Returns the time portion formatted for a given locale and options, without the date. Same locale/options rules as toLocaleDateString.