Borislav Hadzhiev
Sun Jan 23 2022·2 min read
Photo by Farsai Chaikulngamdee
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 create a Date
object.const json = new Date().toJSON(); console.log(json); // 👉️ "2022-01-23T09:04:45.904Z" const date = new Date(json); console.log(date); // 👉️ Sun Jan 23 2022 11:04:45
The
toJSON()
method can be called on a valid Date
object.
You can pass the result from calling the method to the
Date()
constructor to create a Date
object from the JSON string.
Here is the same example, but with a more manual approach.
const json = JSON.stringify(new Date().toISOString()); console.log(json); // 👉️ "2022-01-23T09:04:45.904Z" const date = new Date(JSON.parse(json)); console.log(date); // 👉️ Sun Jan 23 2022 11:04:45 // 👇️ "2022-01-23T09:04:45.904Z" console.log(date.toISOString());
This time 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
.
Note that 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.Because the toISOString
method returns the result according to universal time,
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 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 for a Date
in JavaScript. You
simply have to use the toISOString()
method.
// 👇️ "2022-01-23T09:24:54.995z" console.log(new Date().toISOString());
The string can easily be converted to JSON, by using the JSON.stringify
method
and 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 it as a parameter.
const json = JSON.stringify(new Date().toISOString()); console.log(json); // 👉️ "2022-01-23T09:04:45.904Z" const date = new Date(JSON.parse(json)); console.log(date); // 👉️ Sun Jan 23 2022 11:04:45