JS Built-ins
← Date115 / 120
DatetoJSONbeginner

toJSON() β€” includes year

πŸ“– Usage Example
const d = new Date('2024-01-15T00:00:00.000Z')
d.toJSON()  // β†’ '2024-01-15T00:00:00.000Z'
JSON.stringify({ date: d })  // uses toJSON()

Use toJSON() to get the ISO 8601 UTC string representation of a Date; it is called automatically by JSON.stringify.

Date.prototype.toJSON()

The year is always present at the start of the JSON string.

Challenge: Verify that new Date('2024-01-15T00:00:00.000Z').toJSON().includes('2024') is true.

πŸ’‘ Hints (1)
  • β€’ toJSON() encodes the full ISO 8601 representation, year first