Sub topic 21
Serializing and Storing Temporal Values
A Temporal object only exists while your program runs. To send one over HTTP, write it to a database, or put it in a cache, you need to turn it into text or a number and later rebuild it. This chapter covers how Temporal does that round trip, which format suits each type, and where the round trip can fail.
The chapter assumes you have read the earlier chapters on the Temporal types, parsing with from(), and ZonedDateTime. The examples assume Temporal is in scope, either natively or through the polyfill set up earlier.
The Built-in Round Trip: toJSON and from
Every Temporal type except Temporal.Now has a toJSON() method. It returns the same ISO 8601 string as toString(). JSON.stringify calls toJSON() automatically, so Temporal values serialize without any extra code.
const date = Temporal.PlainDate.from('2024-03-15');
console.log(date.toLocaleString('en-US', { dateStyle: 'long' })); // 'March 15, 2024'
const json = JSON.stringify({ due: date });
console.log(json); // '{"due":"2024-03-15"}'
const restored = Temporal.PlainDate.from(JSON.parse(json).due);
console.log(restored.equals(date)); // trueThe two directions work differently. toLocaleString produces text for people. It depends on locale and is not meant to be parsed back. toJSON produces text for machines. It is fixed, unambiguous, and from() reads it back exactly.
The string itself does not record which type it came from. '2024-03-15' could be a PlainDate, and PlainDateTime.from would also accept it. So no fromJSON exists. Your code has to know which type each field should be.
Reviving Values with a JSON.parse Reviver
When you parse a whole payload, a reviver function can rebuild the Temporal fields in one pass. Map each field name to its type:
const fieldTypes = {
due: Temporal.PlainDate,
createdAt: Temporal.Instant,
meetingAt: Temporal.ZonedDateTime,
length: Temporal.Duration,
};
function temporalReviver(key, value) {
const Type = fieldTypes[key];
return Type && typeof value === 'string' ? Type.from(value) : value;
}
const payload = JSON.stringify({
due: Temporal.PlainDate.from('2024-03-15'),
createdAt: Temporal.Instant.from('2024-03-01T09:30:00Z'),
meetingAt: Temporal.ZonedDateTime.from('2024-03-20T14:00[Europe/Paris]'),
length: Temporal.Duration.from({ minutes: 45 }),
});
console.log(payload);
// {"due":"2024-03-15","createdAt":"2024-03-01T09:30:00Z",
// "meetingAt":"2024-03-20T14:00:00+01:00[Europe/Paris]","length":"PT45M"}
const data = JSON.parse(payload, temporalReviver);
console.log(data.meetingAt.timeZoneId); // 'Europe/Paris'
console.log(data.length.total({ unit: 'minute' })); // 45In a real application, a schema validation library usually does this job. The rule stays the same: the field name or schema decides the type, never the shape of the string.
Choosing a Storage Format per Type
| Type | Serialized form | Typical storage |
|---|---|---|
| Instant | `2024-03-01T09:30:00Z` | `timestamptz` column, or epoch milliseconds or nanoseconds as an integer |
| ZonedDateTime | `2024-03-20T14:00:00+01:00[Europe/Paris]` | Full string, or an instant column plus a time zone ID column |
| PlainDate | `2024-03-15` | `DATE` column |
| PlainDateTime | `2024-03-15T09:00:00` | `timestamp` column without a time zone |
| PlainTime | `09:00:00` | `TIME` column |
| Duration | `PT45M` | Text column, or a total in a fixed unit when the duration has no calendar units |
Store each value as the type it really is. A birthday is a PlainDate. Storing it as midnight UTC brings back the time zone bugs Temporal was designed to remove.
Epoch numbers and BigInt
Instant.epochNanoseconds is a BigInt, and JSON.stringify throws a TypeError on BigInt values. Convert it to a string yourself, or use epochMilliseconds if millisecond precision is enough.
const instant = Temporal.Instant.from('2024-03-01T09:30:00.123456789Z');
const stored = { ns: instant.epochNanoseconds.toString() };
const text = JSON.stringify(stored); // works; a raw BigInt would throw
const back = Temporal.Instant.fromEpochNanoseconds(BigInt(JSON.parse(text).ns));
console.log(back.equals(instant)); // trueAlso check what precision your database keeps. PostgreSQL timestamptz keeps microseconds, so nanosecond digits are lost when you store a value there.
Gotcha: Strings That Do Not Sort
ISO strings with a Z suffix usually sort in time order as plain text. That breaks when the strings have different precision, because toString() leaves out fractional seconds that are zero:
const a = Temporal.Instant.from('2024-03-01T09:30:00Z');
const b = Temporal.Instant.from('2024-03-01T09:30:00.5Z');
console.log([a.toString(), b.toString()].sort());
// ['2024-03-01T09:30:00.5Z', '2024-03-01T09:30:00Z'] (wrong order)
const fixed = [a, b].map((i) => i.toString({ fractionalSecondDigits: 3 }));
console.log(fixed.sort());
// ['2024-03-01T09:30:00.000Z', '2024-03-01T09:30:00.500Z']If stored strings will be sorted or indexed as text, write them at a fixed precision.
Gotcha: Stored Offsets That No Longer Match
A ZonedDateTime string contains both an offset and a time zone ID. When you parse it, from() checks that the two agree. Governments change time zone rules, so a future event saved last year may carry an offset that the current rules reject. By default, from() uses offset: 'reject' and throws a RangeError when they disagree.
const stale = '2024-03-15T12:00:00+01:00[America/New_York]';
try {
Temporal.ZonedDateTime.from(stale);
} catch (e) {
console.log(e instanceof RangeError); // true
}
// Keep the wall-clock time the user chose
console.log(Temporal.ZonedDateTime.from(stale, { offset: 'ignore' }).toString());
// '2024-03-15T12:00:00-04:00[America/New_York]'
// Keep the exact instant that was recorded
console.log(Temporal.ZonedDateTime.from(stale, { offset: 'use' }).toString());
// '2024-03-15T07:00:00-04:00[America/New_York]'Pick the option based on what the value means. For a dentist appointment at noon local time, use 'ignore'. For a record of when something happened, use 'use', or store an Instant instead. The 'prefer' option keeps the stored offset when it is still valid and otherwise falls back to the time zone rules.
Calendar Annotations
A value with a non-ISO calendar serializes with a [u-ca=...] annotation, such as 2024-03-15[u-ca=hebrew], and from() restores the calendar. Many databases and other languages reject this suffix. A common approach is to store the ISO form with toString({ calendarName: 'never' }), store the calendar ID in its own field, and call withCalendar() after parsing.
Exercise
Your API returns {"startsAt":"2025-06-01T10:00:00+02:00[Europe/Berlin]"}. Calling JSON.parse(text).startsAt.add({ days: 1 }) throws. Why, and how do you fix it?
Show answer
JSON.parse returns a plain string, and strings have no add method. JSON carries no type information, so you must rebuild the value yourself, for example with Temporal.ZonedDateTime.from(obj.startsAt) or a reviver that maps the startsAt key to ZonedDateTime.
Exercise
You save a yoga class as '2026-04-05T18:00:00+01:00[Europe/London]'. Before the class, the zone's rules change and parsing starts to throw a RangeError. Which offset option keeps the class at 18:00 local time?
Show answer
Use { offset: 'ignore' }. It discards the stored offset and resolves 18:00 with the current rules for Europe/London. The 'use' option would keep the old exact instant, so the wall-clock time would move.
Exercise
Why does JSON.stringify({ t: instant.epochNanoseconds }) fail, and what are two ways to fix it?
Show answer
epochNanoseconds is a BigInt, and JSON.stringify throws a TypeError for BigInt. You can store epochNanoseconds.toString() and read it back with BigInt() and Instant.fromEpochNanoseconds. Or you can serialize the Instant itself with toString or toJSON.