Date

Date.prototype.toJSON

Returns a string representation of the Date object for use by JSON.stringify, which calls toISOString under the hood

Syntax

JavaScript
date.toJSON()

Return Value

A string representing the date in ISO format, or null for invalid dates

Examples

Basic Usage
const date = new Date('2024-06-15T14:30:00Z');
console.log(date.toJSON()); // '2024-06-15T14:30:00.000Z'
Practical Example
const data = { created: new Date(), name: 'Test' };
const json = JSON.stringify(data);
console.log(json);
// {"created":"2024-06-15T14:30:00.000Z","name":"Test"}
Advanced Usage
const invalid = new Date('invalid');
console.log(invalid.toJSON()); // null

Understanding Date.prototype.toJSON

The Date.prototype.toJSON method in JavaScript returns a string representation of the Date object for use by JSON.stringify, which calls toISOString under the hood. It belongs to the Date object and is one of the most widely used methods for working with date values in modern JavaScript and TypeScript applications.

The method signature is date.toJSON(). When called, it returns a string representing the date in iso format, or null for invalid dates. Understanding when and how to use toJSON() helps you write more expressive, readable code.

Common use cases for Date.prototype.toJSON include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like date-toisostring, json-stringify, enabling you to chain operations together for complex data manipulation pipelines.

Browser support for Date.prototype.toJSON is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.

Browser Compatibility

Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.

Related Methods

More Date Methods

Other methods in the Date object

Related Tools

More Date Methods

Explore JavaScript Methods

Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.