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, that ISO 8601 strings are the only reliably parsed format, and that local and UTC getters are two views of one instant. Here you will use those ideas to move dates between a program, a server, a database, and storage without losing or shifting them.
A Date object cannot leave your program as a live object. JSON, HTTP, localStorage, and most databases accept only text or numbers. So every date you send gets serialized into one of two forms: an ISO 8601 string or an epoch timestamp. The receiver then has to turn it back into a Date.
The Two Wire Formats
const d = new Date(Date.UTC(2024, 2, 10, 14, 5, 9, 42));
console.log(d.toISOString()); // "2024-03-10T14:05:09.042Z"
console.log(d.getTime()); // 1710079509042
// Both round-trip to the same instant
console.log(new Date(d.toISOString()).getTime() === d.getTime()); // true
console.log(new Date(d.getTime()).getTime() === d.getTime()); // truetoISOString always gives the same shape: YYYY-MM-DDTHH:mm:ss.sssZ, in UTC, with exactly three fractional digits. It does not depend on the machine's time zone or locale, so it is safe to compare as text. Two ISO strings in this exact format also sort lexicographically in time order, which helps with log files and string-keyed indexes.
| Format | Example | Strengths | Weaknesses |
|---|---|---|---|
| ISO 8601 string (UTC) | `"2024-03-10T14:05:09.042Z"` | Human-readable, self-describing, sortable as text | Longer, needs parsing |
| Epoch milliseconds | `1710079509042` | Compact, cheap to compare and subtract | Opaque in logs, easy to confuse with seconds |
| Epoch seconds | `1710079509` | Standard in Unix tools, JWTs, many backends | Loses milliseconds, needs a factor of 1000 in JS |
JSON: Automatic on the Way Out, Manual on the Way In
JSON.stringify checks each value for a toJSON method. Date.prototype.toJSON calls toISOString, so dates serialize without any extra work.
const event = { name: "launch", at: new Date(Date.UTC(2024, 2, 10, 14, 5, 9, 42)) };
const json = JSON.stringify(event);
console.log(json); // {"name":"launch","at":"2024-03-10T14:05:09.042Z"}
const back = JSON.parse(json);
console.log(typeof back.at); // "string" -- not a Date!
console.log(back.at instanceof Date); // falseJSON.parse has no idea that a string used to be a date. Any code that calls back.at.getTime() will throw a TypeError. You have two ways to fix this. You can convert specific known fields after parsing, or you can pass a reviver function.
const ISO_UTC = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/;
function reviveDates(key, value) {
if (typeof value === "string" && ISO_UTC.test(value)) {
const date = new Date(value);
if (!Number.isNaN(date.getTime())) return date;
}
return value;
}
const json = '{"name":"launch","at":"2024-03-10T14:05:09.042Z","note":"2024"}';
const parsed = JSON.parse(json, reviveDates);
console.log(parsed.at instanceof Date); // true
console.log(parsed.at.getTime()); // 1710079509042
console.log(parsed.note); // "2024" (left alone)Sending Timestamps Instead of Strings
Some APIs expect numbers. The replacer argument of JSON.stringify can change the output, but there is a catch. toJSON runs before the replacer, so value is already the ISO string when the replacer sees it. Read the original from this[key] instead. That requires a regular function, not an arrow function.
const event = { name: "launch", at: new Date(Date.UTC(2024, 2, 10, 14, 5, 9, 42)) };
const json = JSON.stringify(event, function (key, value) {
const original = this[key];
return original instanceof Date ? original.getTime() : value;
});
console.log(json); // {"name":"launch","at":1710079509042}Seconds Versus Milliseconds
JavaScript counts milliseconds. Unix tools, JWT exp claims, PostgreSQL's extract(epoch ...), and many APIs count seconds. If you mix them up, you get no error, just a wrong date.
const fromServerSeconds = 1710079509;
console.log(new Date(fromServerSeconds).toISOString());
// "1970-01-20T19:01:19.509Z" -- wrong: treated as milliseconds
console.log(new Date(fromServerSeconds * 1000).toISOString());
// "2024-03-10T14:05:09.000Z" -- correct
const nowSeconds = Math.floor(Date.now() / 1000); // ms -> whole seconds
console.log(Number.isInteger(nowSeconds)); // trueA useful rule of thumb: current timestamps in seconds have 10 digits, and in milliseconds they have 13. Name fields with their unit, such as expiresAtMs or created_epoch_s, so nobody has to guess.
Edge Cases That Break Serialization
Invalid Dates
An Invalid Date behaves differently depending on which method you call:
const bad = new Date("not a date");
console.log(JSON.stringify({ at: bad })); // {"at":null}
console.log(bad.toJSON()); // null
try {
bad.toISOString();
} catch (err) {
console.log(err.name); // "RangeError"
}JSON.stringify quietly writes null, which the server may store as "no date". Validate with Number.isNaN(date.getTime()) before you send.
Years Outside 0000–9999 and the Range Limit
A Date covers ±8.64e15 milliseconds, about ±273,790 years around 1970. For years outside 0 to 9999, toISOString switches to the expanded six-digit format with a sign. Some other systems reject that format.
console.log(new Date(Date.UTC(10000, 0, 1)).toISOString()); // "+010000-01-01T00:00:00.000Z"
console.log(new Date(8.64e15).toISOString()); // "+275760-09-13T00:00:00.000Z"
console.log(new Date(8.64e15 + 1).getTime()); // NaNPrecision Beyond Milliseconds
Databases such as PostgreSQL store microseconds, for example "2024-03-10T14:05:09.123456Z". The ECMAScript date-time format defines only three fractional digits. Whether an engine accepts more digits is implementation-defined, and even when it does, the extra digits are dropped. If microseconds matter, such as for ordering events that happen within the same millisecond, keep the original string or a separate integer field. Do not round-trip that value through Date.
The Offset Is Lost
toISOString always writes UTC. If a user in Tokyo books a meeting for 09:00 local time, the serialized value is "2024-03-11T00:00:00.000Z". The instant is correct, but the fact that the user meant Tokyo time is gone. When the zone matters for display or for repeating events, send it as a separate field:
const booking = {
at: new Date("2024-03-11T09:00:00+09:00").toISOString(), // "2024-03-11T00:00:00.000Z"
timeZone: "Asia/Tokyo",
};
console.log(JSON.stringify(booking));Date-Only Values Are Not Instants
A birthday or a due date names a calendar day, not a moment. If you store it as a Date, it picks up a time and a zone, and it can show up as the wrong day:
const birthday = new Date("1990-05-15"); // date-only ISO: parsed as UTC midnight
console.log(birthday.toLocaleDateString("en-US", { timeZone: "UTC" })); // "5/15/1990"
console.log(birthday.toLocaleDateString("en-US", { timeZone: "America/Los_Angeles" })); // "5/14/1990"Store and send plain-date values as "YYYY-MM-DD" strings and keep them as strings in your model. If you need a Date for calculations, build it with Date.UTC(year, month - 1, day) and read it back only with UTC getters.
Choosing a Format
- Use UTC ISO strings for APIs, logs, and anything people will read. They are unambiguous and they sort correctly.
- Use epoch milliseconds for compact internal data, cache keys, and heavy arithmetic. Write the unit in the field name.
- Use epoch seconds only when the other system requires them, and convert at the boundary.
- Add an IANA zone field when the user's local wall-clock time matters.
- Keep plain dates as
"YYYY-MM-DD"strings.
Exercise
A server returns {"expires": 1735689600}. Your code runs new Date(data.expires) < new Date() and treats the token as expired. Why, and what is the fix?
Show answer
The value has 10 digits, so it is in seconds. new Date(1735689600) reads it as milliseconds, which puts it in January 1970, always in the past. Convert it first: new Date(data.expires * 1000). Better still, rename the field or document its unit.
Exercise
After const copy = JSON.parse(JSON.stringify(state)), calls to copy.updatedAt.getTime() throw a TypeError. Give two ways to fix this.
Show answer
JSON.stringify turned the Date into an ISO string, and JSON.parse left it as a string. One fix is to pass a reviver to JSON.parse that converts updatedAt (by key, or by an ISO pattern) with new Date(value). The other fix, for copies inside one program, is to use structuredClone(state), which keeps Date objects.
Exercise
What does JSON.stringify({ d: new Date("2024-13-01") }) produce, and why might this be dangerous?
Show answer
It produces {"d":null}. Month 13 is invalid, so the Date is an Invalid Date, and toJSON returns null instead of throwing. The server may store this as "no date", so check Number.isNaN(date.getTime()) before you serialize.