Sometimes, we want to parse JSON to receive a Date object in JavaScript.
In this article, we’ll look at how to parse JSON to receive a Date object in JavaScript.
How to parse JSON to receive a Date object in JavaScript?
To parse JSON to receive a Date object in JavaScript, we call JSON.parse
with our own parsing function.
For instance, we write
const dateTimeReviver = (key, value) => {
let a;
if (typeof value === "string") {
a = /\/Date\((\d*)\)\//.exec(value);
if (a) {
return new Date(+a[1]);
}
}
return value;
};
const obj = JSON.parse(jsonString, dateTimeReviver);
to create the dateTimeReviver
functon that checks if the value
being parsed is a string with
typeof value === "string"
Then we get the parts that has /\/Date\((\d*)\)\//
pattern in it with exec
.
If it’s found, then we create a Date
object from it.
Otherwise, we return value
as is.
Then we call JSON.parse
with the jsonString
we want to parse and the dateTimeReviver
function that we created to parse the JSON string with the dates.
Conclusion
To parse JSON to receive a Date object in JavaScript, we call JSON.parse
with our own parsing function.