Creating Dates from JSON
You'll learn how to properly handle date strings when parsing JSON, since JSON.parse() doesn't automatically convert them to Date objects.
The Problem with JSON and Dates
JSON doesn't have a native date type—dates are serialized as strings (typically in ISO 8601 format). When you use JSON.parse() to convert JSON back into JavaScript objects, those date strings remain as strings. They don't magically become Date objects:
const jsonString = '{"name":"Alice","created":"2024-01-15T10:30:00.000Z"}';
const obj = JSON.parse(jsonString);
console.log(typeof obj.created); // "string"
console.log(obj.created); // "2024-01-15T10:30:00.000Z"
Manual Date Construction Required
To get actual Date objects, you must manually construct them from the parsed strings:
const jsonString = '{"name":"Alice","created":"2024-01-15T10:30:00.000Z"}';
const obj = JSON.parse(jsonString);
// Manually convert the string to a Date
obj.created = new Date(obj.created);
console.log(obj.created instanceof Date); // true
console.log(obj.created.getFullYear()); // 2024
The Reviver Function Pattern
JSON.parse() accepts a second parameter—a "reviver" function—that lets you transform values during parsing:
const jsonString = '{"created":"2024-01-15T10:30:00.000Z"}';
const obj = JSON.parse(jsonString, (key, value) => {
// Check if the value looks like an ISO date string
if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T/.test(value)) {
return new Date(value);
}
return value;
});
console.log(obj.created instanceof Date); // true
Key Takeaway: JSON.parse() treats dates as strings; you must manually construct Date objects either after parsing or using a reviver function during parsing.