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.13 kB
import { fractionalDigitsOption } from "./typedOptions.js"; import { zonedDateTimeOf } from "./zonedWallClock.js"; import { zonedUnitEnd, zonedUnitStart } from "./zonedBucket.js"; import { defaultFractionalDigits } from "./defaultFractionalDigits.js"; import { isDateTimeUnitName } from "./unitNames.js"; import { resolveDateTimeUnit } from "./resolveDateTimeUnit.js"; import { resolveWeekStartsOn } from "./resolveWeekStartsOn.js"; // src/internal/startOrEndOfZoned.ts /** * Internal shared implementation for `startOfZoned` / `endOfZoned`. * * - Snaps to the real local bucket from `internal/zonedBucket.ts` in `value`'s own zone: a * start is never after `value`, an end never before it. * - `weekStartsOn` picks the week's first day. An end is written at nanosecond precision by * default (next start − 1 ns); a start's `fractionalSecondDigits` defaults to the unit's own * precision (see `defaultFractionalDigits`). * - `unit` may be singular or plural; an invalid `weekStartsOn` returns "". * * @param value zoned ISO 8601 datetime string * @param unit DateTimeUnit to snap to, singular or plural * @param options optional: weekStartsOn, fractionalSecondDigits * @param isEnd false for start-of-unit, true for end-of-unit * @returns zoned ISO 8601 string, or "" on invalid input */ function startOrEndOfZoned(value, unit, options, isEnd) { const resolvedUnit = resolveDateTimeUnit(unit); const weekStartsOn = resolveWeekStartsOn(options.weekStartsOn); const source = zonedDateTimeOf(value); if (source === null || !isDateTimeUnitName(resolvedUnit) || weekStartsOn === null) return ""; const weekStartDay = weekStartsOn === "monday" ? 1 : 7; const requestedDigits = fractionalDigitsOption(options.fractionalSecondDigits); const fractionalSecondDigits = isEnd ? requestedDigits ?? 9 : defaultFractionalDigits(resolvedUnit, requestedDigits); try { const boundary = isEnd ? zonedUnitEnd(source, resolvedUnit, weekStartDay) : zonedUnitStart(source, resolvedUnit, weekStartDay); return boundary ? boundary.toString({ fractionalSecondDigits }) : ""; } catch { return ""; } } export { startOrEndOfZoned };