Skip to content

truncateNanoseconds

truncateNanoseconds(nanoseconds: bigint, unit: NanosecondTruncationUnit): bigint

Truncate nanoseconds since the Unix epoch to the precision a store can actually hold.

  • 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 either side of the epoch.
  • Call this before writing to a store that cannot hold nanoseconds — PostgreSQL timestamptz and MySQL DATETIME(6) hold microseconds, Date-based APIs hold milliseconds — so the value read back equals the value written.
  • Idempotent: truncating an already-truncated value returns it unchanged.
  • Returns 0n on invalid input, including nanoseconds outside the range Temporal.Instant can represent. 0n is also the epoch itself — validate first when the two must be told apart.
ParameterTypeDescription
nanosecondsbigintnanoseconds since the Unix epoch (bigint)
unitNanosecondTruncationUnittarget storage precision, “ms” (milliseconds) or “us” (microseconds)

truncated nanoseconds as a bigint, or 0n on invalid input

Storage precision a nanosecond value can be truncated to.

import type { NanosecondTruncationUnit } from "@northguild/gmt";
"ms" | "us"
import { truncateNanoseconds } from "@northguild/gmt/precision/calculate";
truncateNanoseconds(1710072000123456789n, "us") // 1710072000123456000n
output 

precision/calculate/truncateNanoseconds.ts