JavaScript date.toJSON() method
The date.toJSON()
method in JavaScript is used to convert a Date
object into a JSON-compatible string format. It internally uses the toISOString()
method, returning the date and time in ISO 8601 format.
Syntax:
Returns:
- A string representing the date in ISO 8601 format, similar to the output of
toISOString()
, in the format:YYYY-MM-DDTHH:mm:ss.sssZ
.
Key Features:
- The
toJSON()
method is typically used when serializingDate
objects to JSON (e.g., when usingJSON.stringify()
). - It ensures that dates are stored in a consistent, universally accepted format.
Example 1: Converting the Current Date to JSON
Output:
Explanation:
- The
toJSON()
method converts the current date to a string in the ISO 8601 format. - The time is expressed in UTC (indicated by
Z
), and milliseconds are included.
Example 2: Serializing a Date Object with JSON.stringify()
Output:
Explanation:
- When using
JSON.stringify()
to convert an object containing aDate
, theDate
object is automatically serialized to a JSON-compatible string using thetoJSON()
method. - The date is represented in ISO format inside the JSON structure.
Example 3: Using toJSON()
with a Specific Date
Output:
Explanation:
- The
toJSON()
method converts the specific date (July 20, 1969 20:18:00
) into ISO 8601 format. - The time zone is adjusted to UTC, and milliseconds are included as
.000
.
Example 4: toJSON()
on Invalid Date
Output:
Explanation:
- If the
Date
object is invalid,toJSON()
returnsnull
instead of a string.
Summary:
date.toJSON()
is used to convert aDate
object into a JSON-compatible ISO 8601 string format.- It is often invoked automatically during
JSON.stringify()
and is especially useful when serializing objects containingDate
values. - The result is always in UTC, and it returns
null
for invalidDate
objects.