Sub topic 7
Storing and Sending Dates: ISO Strings, JSON, and Timestamps
This chapter assumes you know that a Date wraps a millisecond time value, and that a date-only ISO string is parsed as UTC while a date-time string with no offset is parsed as local time. Both topics were covered in earlier chapters. This chapter covers what happens when a date leaves your program: when you write it to a database, send it over HTTP, or put it in local storage.
The rule is to send the instant and leave out the wall-clock view of it. You have two reliable ways to do that: an ISO 8601 string in UTC, or a number of epoch milliseconds.
ISO Strings and JSON
toISOString() always prints in UTC. The output has millisecond precision and a trailing Z, whatever the machine's time zone is. JSON.stringify calls a date's toJSON method, and toJSON calls toISOString, so dates become ISO strings automatically.
The reverse step does not happen on its own. JSON.parse has no way to know which strings were dates, so it gives you strings back.
const d = new Date(Date.UTC(2024, 6, 4, 16, 30));
console.log(d.toISOString()); // "2024-07-04T16:30:00.000Z"
const payload = JSON.stringify({ id: 7, createdAt: d });
console.log(payload); // {"id":7,"createdAt":"2024-07-04T16:30:00.000Z"}
const back = JSON.parse(payload);
console.log(typeof back.createdAt); // "string"To get Date objects back, pass a reviver function. JSON.parse calls the reviver for every key and value, and the reviver can replace a value with something else. Match the exact format you produce so that an ordinary string doesn't get converted by accident.
const ISO_UTC = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;
function reviveDates(key, value) {
return typeof value === "string" && ISO_UTC.test(value) ? new Date(value) : value;
}
const payload = '{"id":7,"createdAt":"2024-07-04T16:30:00.000Z"}';
const restored = JSON.parse(payload, reviveDates);
console.log(restored.createdAt instanceof Date); // true
console.log(restored.createdAt.getTime()); // 1720110600000Epoch Timestamps
Epoch milliseconds are compact, sort as plain numbers, and need no parsing. Many backends and Unix tools count in seconds instead, so convert at the boundary and make the unit clear in the field name.
const d = new Date("2024-07-04T16:30:00Z");
const ms = d.getTime(); // 1720110600000
const unixSeconds = Math.floor(ms / 1000); // 1720110600
const fromSeconds = new Date(unixSeconds * 1000);
console.log(fromSeconds.toISOString()); // "2024-07-04T16:30:00.000Z"Invalid Dates
An Invalid Date behaves differently depending on how you serialize it. toISOString throws a RangeError, but toJSON returns null. That means JSON.stringify quietly writes null into your payload.
const bad = new Date("nope");
console.log(JSON.stringify({ t: bad })); // {"t":null}
try {
bad.toISOString();
} catch (err) {
console.log(err.name); // "RangeError"
}Check Number.isNaN(date.getTime()) before you send a date.
Choosing a Format
| Format | Readable | Sorts correctly | Typical use |
|---|---|---|---|
| ISO string with `Z` | Yes | Yes, as text, if every value has the same layout | JSON APIs, logs, config files |
| Epoch milliseconds | No | Yes, as numbers | Databases, caches, measuring durations |
| Local string without offset | Yes | No | Avoid for storage, because the instant it refers to is ambiguous |
Use the user's local time when you display a date. For storage and transfer, keep it in UTC.
Exercise
A server returns {"due":"2024-12-01T09:00:00.000Z"}. After JSON.parse, your code calls data.due.getTime() and throws "getTime is not a function". Why does this happen, and what are two ways to fix it?
Show answer
JSON.parse returns the ISO value as a string, not a Date. You can wrap the field yourself with new Date(data.due), or you can pass a reviver to JSON.parse that turns ISO UTC strings into Date objects.
Exercise
A field holds 1733043600. new Date(1733043600) prints a date in January 1970. What went wrong?
Show answer
The value is in Unix seconds, but the Date constructor expects milliseconds. Use new Date(1733043600 * 1000).