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

2 Answers

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

// Define the expected shape of the parsed JSON
interface Payload {
  id: number;
  createdAt: string; // JSON always gives strings, not Date objects
}

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

// Convert the ISO‑8601 string into a real Date instance
// JavaScript's Date constructor understands ISO strings natively
const JSONDate: Date = 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
0 votes
// JSON with a date string
const json = `{
  "id": 42,
  "createdAt": "2025-03-19T14:22:30.000Z"
}`;

// Define the expected structure of the parsed JSON
interface Payload {
  id: number;
  createdAt: string; // JSON always stores dates as strings
}

// A type‑safe date parser
function parseJsonDate(str: string): Date | null {
  const date: Date = new Date(str);

  return isNaN(date.getTime()) ? null : date;
}

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

// Convert the date string into a real Date instance
const JSONDate = parseJsonDate(data.createdAt);

if (!JSONDate) {
  throw new Error("Invalid date in JSON");
}

// 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
...