Sub topic 8
Exact Moments with Temporal.Instant
This chapter assumes you have read the type overview and know the difference between exact time and wall-clock time. It also assumes you can load Temporal natively or through the polyfill, and that you are comfortable with JavaScript BigInt values.
A Temporal.Instant is a single point on the global timeline. It has no time zone, no calendar, and no year, month, or day fields. Internally it is one number: the count of nanoseconds since the Unix epoch, 1970-01-01T00:00:00Z. Two people in Tokyo and Paris who call Temporal.Now.instant() at the same moment get equal instants, even though their wall clocks show different times.
Use Instant for anything that records when something happened. Log timestamps, event-sourcing records, token expiry times, and database "created at" columns all fit this description.
The internal model
An instant stores one value, epochNanoseconds, as a BigInt. All other output is derived from that number.
The examples below assume Temporal is in scope. If your runtime lacks it, start each script with the fallback from the runtime-support chapter:
import { Temporal as TemporalPolyfill } from '@js-temporal/polyfill';
const Temporal = globalThis.Temporal ?? TemporalPolyfill;
const instant = Temporal.Instant.from('2024-03-15T12:00:00Z');
console.log(instant.epochMilliseconds); // 1710504000000
console.log(instant.epochNanoseconds); // 1710504000000000000n
console.log(instant.toString()); // '2024-03-15T12:00:00Z'epochMilliseconds is a regular Number. epochNanoseconds is a BigInt because nanosecond counts for modern dates go beyond Number.MAX_SAFE_INTEGER.
Creating instants
You can create an instant in four ways:
| Method | Input | Typical source |
|---|---|---|
| `Temporal.Instant.from(string)` | ISO 8601 string with `Z` or a numeric offset | APIs, logs, JSON |
| `Temporal.Instant.fromEpochMilliseconds(n)` | `Number` | `Date.now()`, legacy `Date`, JavaScript-based databases |
| `Temporal.Instant.fromEpochNanoseconds(n)` | `BigInt` | High-precision clocks, other languages |
| `new Temporal.Instant(n)` | `BigInt` nanoseconds | Same as above, constructor form |
Temporal.Now.instant() returns the current moment.
Strings must pin down an exact moment
A string can only become an instant if it identifies one moment on the global timeline. That means it needs a Z or a UTC offset. Temporal does not guess a time zone the way new Date('2024-03-15T12:00:00') silently uses local time.
// The offset is applied, then the value is stored as UTC
const withOffset = Temporal.Instant.from('2024-03-15T12:00:00+02:00');
console.log(withOffset.toString()); // '2024-03-15T10:00:00Z'
try {
Temporal.Instant.from('2024-03-15T12:00:00'); // no Z, no offset
} catch (e) {
console.log(e instanceof RangeError); // true
}Numeric inputs and their types
fromEpochNanoseconds and the constructor accept only BigInt. Passing a Number throws a TypeError, so a value can never be silently rounded to the nearest representable double.
const ns = Temporal.Instant.fromEpochNanoseconds(1710504000000000001n);
console.log(ns.toString()); // '2024-03-15T12:00:00.000000001Z'
try {
Temporal.Instant.fromEpochNanoseconds(1710504000000000000);
} catch (e) {
console.log(e instanceof TypeError); // true
}Instants are limited to 100,000,000 days on either side of the epoch, which is the same range as Date. Values outside it throw a RangeError.
Displaying an instant
toString() prints UTC with a Z suffix by default. Pass a timeZone to render the same moment with that zone's offset. The instant itself does not change.
const instant = Temporal.Instant.from('2024-03-15T12:00:00.123456789Z');
console.log(instant.toString());
// '2024-03-15T12:00:00.123456789Z'
console.log(instant.toString({ timeZone: 'Asia/Tokyo' }));
// '2024-03-15T21:00:00.123456789+09:00'
console.log(instant.toString({ smallestUnit: 'second' }));
// '2024-03-15T12:00:00Z'Note that smallestUnit truncates by default. It does not round. Other chapters cover locale formatting and rounding in detail.
What an instant cannot do
An instant has no calendar fields. instant.year is undefined, and so are month and hour. To read those fields, convert the instant to a wall-clock view with toZonedDateTimeISO(timeZone).
This also limits arithmetic. An instant accepts hours, minutes, seconds, and smaller units, because those have a fixed length. Days, weeks, months, and years throw a RangeError. The length of a day depends on a time zone (a daylight saving day can last 23 or 25 hours), and an instant has no time zone.
const start = Temporal.Instant.from('2024-03-15T12:00:00Z');
console.log(start.add({ hours: 36 }).toString()); // '2024-03-17T00:00:00Z'
try {
start.add({ days: 1 });
} catch (e) {
console.log(e instanceof RangeError); // true
}
// For calendar arithmetic, go through ZonedDateTime
const nextDay = start
.toZonedDateTimeISO('America/New_York')
.add({ days: 1 })
.toInstant();
console.log(nextDay.toString()); // '2024-03-16T12:00:00Z'In the same way, until and since on instants return durations in seconds by default, never days. Later chapters cover differences, comparison, and sorting.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `RangeError` parsing a string | String has no `Z` or offset | Add an offset, or parse as `PlainDateTime` and then attach a zone |
| `TypeError` from `fromEpochNanoseconds` | Passed a `Number` | Use a `BigInt` literal (`123n`) or `BigInt(value)` |
| `RangeError` from `add({ days })` | Instants have no calendar | Convert to `ZonedDateTime` first |
| Precision lost after converting to `Date` | `Date` stores milliseconds only | Keep the instant, or store `epochNanoseconds` as a string |
| `instant.hour` is `undefined` | Instants have no fields | Call `toZonedDateTimeISO(zone)` |
Exercise
What does Temporal.Instant.from('2024-06-01T09:30:00-07:00').toString() print, and would Temporal.Instant.from('2024-06-01T09:30:00') succeed?
Show answer
It prints '2024-06-01T16:30:00Z', because the -07:00 offset is converted to UTC. The second call throws a RangeError, because the string has no Z or offset and so does not identify an exact moment.
Exercise
A token is issued at instant issued and must expire exactly 7 days later. Why does issued.add({ days: 7 }) fail, and what should you write instead if "7 days" means 168 elapsed hours?
Show answer
Instant arithmetic rejects days because a day's length depends on a time zone, so the call throws a RangeError. For 168 fixed hours, write issued.add({ hours: 168 }). If you instead mean "the same wall-clock time 7 calendar days later in a given zone", convert with toZonedDateTimeISO(zone), add { days: 7 }, then call toInstant().
Exercise
You receive the nanosecond timestamp 1710504000000000001 as a JSON number. Why is that a problem, and how should the producer send it?
Show answer
JSON numbers parse to JavaScript Numbers, which cannot exactly represent integers above 2^53 - 1. The value gets rounded before it reaches Temporal, and fromEpochNanoseconds rejects a Number anyway. The producer should send it as a string, which you convert with Temporal.Instant.fromEpochNanoseconds(BigInt(str)), or send an ISO string with nanosecond digits and parse it with Temporal.Instant.from.