How to convert JSON with date string into a date in JavaScript

2 Answers

0 votes
// JSON with a date string
const json = `{
  "id": 42,
  "createdAt": "2025-03-19T14:22:30.000Z"
}`;

// Parse the JSON into a JS object
const data = JSON.parse(json);

// Convert the ISO‑8601 string into a real Date instance
// JavaScript's Date constructor understands ISO strings natively
const JSONDate = new Date(data.createdAt);

// Use it like any Date object
console.log(JSONDate.toISOString());  
console.log(JSONDate.getFullYear());   
console.log(JSONDate instanceof Date); 



/*
run:

2025-03-19T14:22:30.000Z
2025
true

*/

 



answered Mar 19 by avibootz
edited Mar 19 by avibootz
0 votes
// JSON with a date string
const json = `{
  "id": 42,
  "createdAt": "2025-03-19T14:22:30.000Z"
}`;
 
 
function parseJsonDate(str) {
  const date = new Date(str);
   
  return isNaN(date.getTime()) ? null : date;
}
 
// Parse the JSON into a JS object
const data = JSON.parse(json);
 
const JSONDate = parseJsonDate(data.createdAt);
 
// Use it like any Date object
console.log(JSONDate.toISOString()); 
console.log(JSONDate.toLocaleString()); // Human‑readable local time
console.log(JSONDate.getFullYear());  
console.log(JSONDate instanceof Date); 
 
 
/*
run:
 
2025-03-19T14:22:30.000Z
3/19/2025, 2:22:30 PM
2025
true

*/

 



answered Mar 19 by avibootz
edited Mar 19 by avibootz

Related questions

...