UNPKG

@northguild/gmt

Version:

Date and time library for JavaScript and TypeScript, built on TC39 Temporal: time zones, DST, business days, ISO 8601 strings in and out. Never throws.

42 lines (40 loc) • 2.47 kB
import { floorDivide } from "../../internal/floorDivide.js"; import { NANOSECONDS_PER_SECOND, PROTO_TIMESTAMP_MAX_SECONDS, PROTO_TIMESTAMP_MIN_SECONDS } from "../../internal/foreignEpochs.js"; import { parseInstantNanoseconds } from "../../internal/instantNanoseconds.js"; // src/precision/convert/toProtoTimestamp.ts /** * Convert an ISO 8601 instant string to a protobuf `google.protobuf.Timestamp` record. * * - `nanos` always counts **forward** from `seconds`, also for instants before the epoch: half a * second before 1970 is `{ seconds: -1n, nanos: 500000000 }`, never `{ seconds: 0n, nanos: -500000000 }`. * - Exact: nothing is rounded. An offset or zone in the input is applied first. * - `seconds` is a `bigint` (`int64`). The range is the one `timestamp.proto` states, * 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z; an instant outside it returns `null`. * - A leap second (`23:59:60`) is invalid: protobuf smears leap seconds, so it has no value here. * - Returns `null` on invalid input. * * @param isoString ISO 8601 instant string (e.g. "2024-03-10T12:34:56.789Z") * @returns `{ seconds, nanos }`, or `null` on invalid input * * @example toProtoTimestamp("1970-01-01T00:00:00Z") // { seconds: 0n, nanos: 0 } * @example toProtoTimestamp("1969-12-31T23:59:59.5Z") // { seconds: -1n, nanos: 500000000 } — nanos count forward * @example toProtoTimestamp("2024-03-10T12:34:56.789Z") // { seconds: 1710074096n, nanos: 789000000 } * @example toProtoTimestamp("2024-03-10T13:34:56.789+01:00[Europe/Paris]") // { seconds: 1710074096n, nanos: 789000000 } * @example toProtoTimestamp("0001-01-01T00:00:00Z") // { seconds: -62135596800n, nanos: 0 } * @example toProtoTimestamp("9999-12-31T23:59:59.999999999Z") // { seconds: 253402300799n, nanos: 999999999 } * @example toProtoTimestamp("+010000-01-01T00:00:00Z") // null — past the protobuf range * @example toProtoTimestamp("2016-12-31T23:59:60Z") // null — leap second * @example toProtoTimestamp("2024-03-10T12:34:56") // null — no offset designator * @example toProtoTimestamp("invalid") // null */ function toProtoTimestamp(isoString) { const nanoseconds = parseInstantNanoseconds(isoString); if (nanoseconds === null) return null; const seconds = floorDivide(nanoseconds, NANOSECONDS_PER_SECOND); if (seconds < -62135596800n || seconds > 253402300799n) return null; return { seconds, nanos: Number(nanoseconds - seconds * NANOSECONDS_PER_SECOND) }; } export { toProtoTimestamp };