Last updated: Mar 6, 2024
Reading timeยท3 min
To parse a JSON date:
toJSON()
method to get a string representation of the Date
object.Date()
constructor.Date()
constructor will parse the ISO string and will create a Date
object.const json = new Date().toJSON(); console.log(json); // ๐๏ธ "2023-07-27T09:53:51.111Z" const date = new Date(json); console.log(date); // ๐๏ธ Thu Jul 27 2023 12:54:06
The
toJSON()
method can be called on a valid Date
object.
You can pass the result of calling the method to the
Date() constructor to create a
Date
object from the JSON string.
Here is the same example, but using a more manual approach.
const json = JSON.stringify(new Date().toISOString()); console.log(json); // ๐๏ธ "2023-07-27T09:55:15.209Z" const date = new Date(JSON.parse(json)); console.log(date); // ๐๏ธ Thu Jul 27 2023 12:55:38 // ๐๏ธ "2023-07-27T09:55:15.209Z" console.log(date.toISOString());
We used the
toISOString()
method to get a string that represents the given date in the ISO 8601 format -
YYYY-MM-DDTHH:mm:ss.sssZ
.
When using the toISOString
method, you always get a date according to
universal time.
toJSON()
method uses the toISOString()
method under the hood, so the two code snippets are equivalent, with the second one being more explicit.The toISOString
method returns the result according to Universal Time, so the
string shows a time of 09:04:45
, whereas the Date
object has its time set to
11:04:45
.
This is because my time zone is 2
hours ahead of Coordinated Universal Time
(UTC).
When it comes to storing dates, most of the time, it is advised to store a timestamp or a valid ISO 8601 string (UTC) in your database.
For consistency, you should mostly use local time when you have to render a date and time to the user, but store the actual values in UTC (=GMT).
It is quite easy to
get an ISO-formatted string of a Date
in JavaScript. You simply have to use the toISOString()
method.
// ๐๏ธ "2023-07-27T09:56:46.833Z" console.log(new Date().toISOString());
The string can easily be converted to JSON by using the JSON.stringify()
method and can then be transmitted over the network.
The Date()
constructor knows how to parse ISO 8601 strings, so all you have to
do is parse the JSON and pass the ISO string to the constructor.
const json = JSON.stringify(new Date().toISOString()); console.log(json); // ๐๏ธ "2023-07-27T09:56:59.806Z" const date = new Date(JSON.parse(json)); console.log(date); // ๐๏ธ Thu Jul 27 2023 12:57:08
You can learn more about the related topics by checking out the following tutorials: