Thursday, 28 May 2020

JSON - How to the parse the date? | JSON Tutorial

Boost Your Coding Skills!

Subscribe to Ram N Java for beginner-friendly programming lessons, web development concepts, and practical coding tips!

Subscribe to YouTube Channel

Introduction: The JSON Date Problem

One of the most surprising quirks for developers starting with JSON is discovering that JSON does not have a native Date data type.

When you send or receive dates in JSON, they are usually converted into standard ISO-8601 text strings (for example, "2026-10-29T05:30:00.000Z") or timestamps. When you pass that text into JSON.parse(), it remains a plain string—not a JavaScript Date object. To perform date math, formatting, or comparisons, you need reliable techniques to convert them back into true Date objects.

Technique 1: Manual Conversion After Parsing

The simplest, most straightforward approach is to parse your JSON as usual and then manually pass the date string into the new Date() constructor:

const jsonStr = '{"event": "Webinar", "date": "2026-10-29T10:00:00Z"}';
const data = JSON.parse(jsonStr);

// Convert string to Date object
data.date = new Date(data.date);

console.log(data.date.getFullYear()); // Outputs: 2026

This technique works perfectly when you know exactly which fields contain dates.

Technique 2: Automatic Parsing with a Reviver Function

If your payload contains multiple date fields or nested structures, converting each one manually can become repetitive. Instead, you can use the reviver parameter built right into JSON.parse():

const jsonStr = '{"event": "Launch", "created_at": "2026-10-29T10:00:00Z"}';

const data = JSON.parse(jsonStr, function(key, value) {
  if (key === "created_at") {
    return new Date(value);
  }
  return value;
});

console.log(data.created_at instanceof Date); // Outputs: true

Best Practices for Handling Dates in JSON

  • Standardize on ISO-8601: Always format dates as UTC strings (e.g., YYYY-MM-DDTHH:mm:ss.sssZ) on the backend to avoid timezone misinterpretations across client browsers.
  • Validate Before Parsing: When using reviver functions across large datasets, verify that incoming date strings are valid before constructing new Date() to prevent Invalid Date values.
  • Keep Serialization Predictable: When sending dates back to an API, calling JSON.stringify() automatically converts JavaScript Date objects into ISO format via toISOString().

Related Video Tutorials from Ram N Java

Explore more helpful JSON and JavaScript lessons from our channel:

No comments:

Post a Comment

Tutorials