# Nanosecond Precision

Industry: Core

[`convertZonedToUnix`](/gmt/reference/zoned/convert/convertZonedToUnix/) and its siblings return
`number` milliseconds. Systems that record telemetry, trades or sensor readings need
nanoseconds, and a `number` cannot hold them. Integers are exact only to `2^53 − 1`, about
9.0 × 10^15, and nanoseconds since the epoch passed that in April 1970.

`Date.now() * 1e6` is not a nanosecond timestamp. It is a millisecond timestamp with three
zeroes appended.

The `precision/` namespace works in `bigint`:

```typescript
import {
  toNanoseconds,
  fromNanoseconds,
  formatNanoseconds,
  parseNanoseconds,
  truncateNanoseconds,
} from "@northguild/gmt";

toNanoseconds("2024-03-10T12:00:00.123456789Z");
// 1710072000123456789n

fromNanoseconds(1710072000123456789n);
// "2024-03-10T12:00:00.123456789Z"

fromNanoseconds(1710072000123456789n, "Asia/Tokyo");
// "2024-03-10T21:00:00.123456789+09:00[Asia/Tokyo]"
```

## Send a nanosecond value over a wire

`JSON.stringify` throws a `TypeError` on a `bigint`, so the value crosses a wire as a
canonical decimal string:

```typescript
JSON.stringify({ observedAt: formatNanoseconds(1710072000123456789n) });
// '{"observedAt":"1710072000123456789"}'

parseNanoseconds("1710072000123456789");
// 1710072000123456789n
```

## Truncate before you store

Most storage engines cannot hold nanoseconds. PostgreSQL `timestamptz` and MySQL
`DATETIME(6)` hold microseconds, so a naive write-then-read loses the last digits silently.
Truncate to the target precision first, and the round trip is exact:

```typescript
truncateNanoseconds(1710072000123456789n, "us");
// 1710072000123456000n — safe to write to a microsecond column

truncateNanoseconds(1710072000123456789n, "ms");
// 1710072000123000000n
```

Truncation floors toward negative infinity, so pre-1970 values truncate the same way
post-1970 ones do. `truncateNanoseconds(-1500n, "us")` is `-2000n`, not `-1000n`. Rounding
toward zero would make the result jump direction on either side of the epoch.

## Tell the epoch from the sentinel

`0n` is both the epoch and the invalid-input sentinel, so `precision/validate` exists to
tell them apart. Each predicate accepts exactly what its partner parses:

```typescript
import {
  isValidInstant,
  isValidNanoseconds,
  isValidNanoPattern,
} from "@northguild/gmt";

isValidInstant("1970-01-01T00:00:00Z"); // true  — toNanoseconds returns 0n, the epoch
isValidInstant("garbage"); // false — toNanoseconds returns 0n, the sentinel

isValidNanoPattern("0"); // true  — parseNanoseconds returns 0n, the epoch
isValidNanoPattern("1e18"); // false

isValidNanoseconds(0n); // true  — in range for truncateNanoseconds / fromNanoseconds
isValidNanoseconds(0); // false — a number cannot carry a nanosecond timestamp
```

Reach for `isValidInstant` rather than `isValidUtc`. The latter gates on the library's
stricter `<date>T<time>Z` shape and rejects the offsets and bracketed zones that
`toNanoseconds` accepts, so validating with it discards valid input.

## Limits

Every `precision/` function returns a sentinel (`""` for strings, `0n` for bigints) on
invalid input. It accepts only values inside the range `Temporal.Instant` can represent,
`±8_640_000_000_000_000_000_000n`. `0n` is also the epoch itself, so validate the input
first when the two must be told apart.

Leap-second-aware time scales (TAI and the satellite clocks) are not part of this namespace.
These are plain instant conversions. See [Leap Seconds and
TAI](/gmt/guides/core-date-operations/leap-seconds-and-tai/) and [GNSS: System Time and Week
Rollover](/gmt/guides/industries/gnss-system-time-and-week-rollover/).

## A zoned string names one instant in every reader

Temporal writes a zone's offset rounded to the minute. A zone with a sub-minute offset is
therefore written with an offset up to 30 seconds from the real one. `Africa/Monrovia`
stood at −00:44:30 until 1972 and is written `-00:45`.

An instant reader takes exactly `Z` or a written offset, and nothing after it: a bracketed
zone, a calendar annotation or any other annotation makes the string invalid. A function that
keeps the zone reads a zoned string through `Temporal.ZonedDateTime.from`'s rules, and
TC39 `ToTemporalZonedDateTime` matches a minute-precision offset by minutes. A zoned string
the library wrote therefore reads back, in a zoned function, as the instant it was written for:

```typescript
import { isValidZonedDateTime, toNanoseconds } from "@northguild/gmt";

toNanoseconds("1960-01-01T00:20:00-00:45"); // -315615300000000000n (01:05:00Z; the offset is exact)
toNanoseconds("1960-01-01T00:20:00-00:45[Africa/Monrovia]"); // 0n (an instant reader takes no bracket)
toNanoseconds("2024-06-15T10:00:00Z[Not/AZone]"); // 0n

isValidZonedDateTime("1960-01-01T00:20:00-00:45[Africa/Monrovia]"); // true  (the rounded offset)
isValidZonedDateTime("1960-01-01T00:20:00-00:44:30[Africa/Monrovia]"); // true  (the exact offset)
isValidZonedDateTime("1960-01-01T00:20:00-00:45:00[Africa/Monrovia]"); // false (an offset with seconds must be exact)
```

- **Where the rule applies.** Instant readers (`precision/`, `span/`, `interval/`, `calendar/`,
  `intermodal/`, `transport/` and `getTimeZoneOffset`) take `Z` or an offset only. The
  functions that keep the zone (`isValidZonedDateTime`, `transitTime`, `toOffsetInstant`,
  every `zoned/` function and a zoned `relativeTo`) take the zoned body and the bracket only.
- **Functions that keep the zone reject a contradiction.** They reject a bracket that
  contradicts the offset, and require an offset written with seconds to be the zone's
  offset exactly.
- **Two limits are Temporal's own.** A wall time repeated inside a sub-minute offset change,
  written to the minute, reads as its first pass (`1952-10-15T23:59:59-11:20[Pacific/Niue]`).
  Write the offset with seconds (`-11:20:00`) to name the second. A zoned read also refuses
  a local date of −271821-04-19, which a zone west of Greenwich shows for the first hours of
  the instant range. Pass that instant in `Z` form to an instant reader.

## See also

- [Spans](../spans/): exact elapsed time between two instants, as a number
- [Foreign Epoch Bridges](/gmt/guides/conversion/foreign-epoch-bridges/): NTP, `FILETIME`, .NET ticks, Excel and PostgreSQL
- [`toNanoseconds` reference](/gmt/reference/precision/convert/toNanoseconds/)
- [`fromNanoseconds` reference](/gmt/reference/precision/convert/fromNanoseconds/)
- [`formatNanoseconds` reference](/gmt/reference/precision/format/formatNanoseconds/)
- [`parseNanoseconds` reference](/gmt/reference/precision/parse/parseNanoseconds/)
- [`truncateNanoseconds` reference](/gmt/reference/precision/calculate/truncateNanoseconds/)
- [`isValidInstant` reference](/gmt/reference/precision/validate/isValidInstant/)
- [`isValidNanoPattern` reference](/gmt/reference/precision/validate/isValidNanoPattern/)
- [`isValidNanoseconds` reference](/gmt/reference/precision/validate/isValidNanoseconds/)
- [`isValidZonedDateTime` reference](/gmt/reference/zoned/validate/isValidZonedDateTime/)
