When working with JSON in JavaScript, it's common to encounter date values that need formatting. Sometimes the format is standard and clean, and other times it comes in strange serialized forms. Knowing how to properly convert and format these values is essential for working with time-related data in a frontend application.
π Standard ISO Date Format
When the date value is already in ISO format, itβs straightforward:
const date = new Date("2022-06-07T00:00:00Z");
const jsonDate = date.toJSON();
The result in jsonDate
will be:
"2022-06-07T00:00:00.000Z"
You can also format it more readably using:
const formatted = date.toLocaleDateString(); // "6/7/2022" (based on locale)
const full = date.toLocaleString(); // "6/7/2022, 12:00:00 AM"
π§ Non-Standard JSON Dates (Microsoft Style)
If the date comes in a format like this:
/Date(1224043200000)/
Youβll need to manually convert it:
const jsonDate = "/Date(1224043200000)/";
const timestamp = parseInt(jsonDate.substr(6));
const date = new Date(timestamp);
You can now format this date
object using standard methods.
π« Best Practice: Avoid Microsoft JSON Dates
Microsoft-style /Date(...)
formats are outdated and inconsistent. The best approach is to modify your server settings to return ISO 8601 date strings.
For example, in .NET you can configure JSON serialization like this:
options.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
This will return clean strings like:
"2022-06-07T00:00:00Z"
π Summary
β Use
Date.toJSON()
orDate.toISOString()
for sending datesπ Use
Date.toLocaleDateString()
or libraries likedayjs
ordate-fns
for formattingβ Avoid
/Date(...)
formats if you canπ Convert timestamp values with
new Date(parseInt(...))
if needed
Understanding the different JSON date formats and how to handle them ensures your frontend code stays clean, readable, and reliable.