CKTIS / JavaScript
Date.prototype.toJSON: Date in JSON serialization
toJSON returns ISO text for a valid date, null for an invalid one, and is invoked automatically by JSON.stringify.
Version: ECMAScript 5 (2009) onward; example target: Node.js 24.22.2
Syntax
date.toJSON(key)date.toJSON(key) normally returns the same string as date.toISOString(). JSON.stringify calls it and passes the property key, but the standard algorithm does not use the key argument. For an invalid Date, numeric conversion is non-finite, so the method returns null instead of throwing the RangeError from toISOString().
The method is intentionally generic: it first obtains a primitive with number hint. Only when that primitive is a non-finite Number does it return null; otherwise it invokes the receiver’s toISOString property. It can therefore work on a non-Date object. It throws if conversion throws, or if toISOString is not callable or throws.
JSON preserves the instant in UTC text but loses the Date type; parsing JSON gives a string. The method has been standard since ECMAScript 5 (2009).
Examples
const payload = {
when: new Date("2024-01-02T03:04:05.006Z"),
missing: new Date(NaN),
};
console.log(JSON.stringify(payload));
console.log(payload.when.toJSON());
const custom = {valueOf: () => 0, toISOString: () => "custom-time"};
console.log(Date.prototype.toJSON.call(custom));Result
{"when":"2024-01-02T03:04:05.006Z","missing":null}
2024-01-02T03:04:05.006Z
custom-time