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.

459 lines (457 loc) • 21.7 kB
import { Temporal } from "./temporal.js"; import { isCalendarArithmeticCompatNeeded } from "./temporalCompat/capabilities.js"; import { calendarFieldsOf } from "./temporalCompat/calendarFields.js"; import { calendarDateFromFields } from "./temporalCompat/calendarDateFromFields.js"; import { calendarDateAdd, calendarDateUntil } from "./temporalCompat/calendarDateArithmetic.js"; import { zonedNextTransition, zonedPreviousTransition } from "./zonedWallClockOperations.js"; import { floorDivide } from "./floorDivide.js"; import { NANOSECONDS_PER_DAY } from "./foreignEpochs.js"; import { ISO_WEEKDAYS, isoFieldsOf, isoWeekdayOf } from "./epochDay.js"; import { offsetTimeline } from "./offsetTimeline.js"; import { DURATION_FIELD_BY_UNIT, getUnitSpan } from "./intervalCountHelpers.js"; // src/internal/zonedBucket.ts /** The `Temporal.Duration` that advances a wall clock by one `unit`. */ function oneUnit(unit) { return unit === "quarter" ? { months: 3 } : { [DURATION_FIELD_BY_UNIT[unit]]: 1 }; } /** Wall-clock fields that a local day, week, month or year boundary resets. */ const MIDNIGHT = { hour: 0, minute: 0, second: 0, millisecond: 0, microsecond: 0, nanosecond: 0 }; /** * Wall-clock fields each unit's boundary resets. `week` is computed from the week start, and * `nanosecond` resets nothing, so neither is listed. */ const FIELDS_RESET_BY_UNIT = { year: { month: 1, day: 1, ...MIDNIGHT }, month: { day: 1, ...MIDNIGHT }, day: MIDNIGHT, hour: { minute: 0, second: 0, millisecond: 0, microsecond: 0, nanosecond: 0 }, minute: { second: 0, millisecond: 0, microsecond: 0, nanosecond: 0 }, second: { millisecond: 0, microsecond: 0, nanosecond: 0 }, millisecond: { microsecond: 0, nanosecond: 0 }, microsecond: { nanosecond: 0 } }; /** * Transitions walked over while sizing one bucket. * * Only transitions inside the bucket matter. No IANA zone has had more than two inside one * local month, but `Africa/Cairo` had four inside local 2010 (DST, suspended for Ramadan, then * resumed and ended), and the walk needs one step past the last of them to see it has left * the bucket — so the bound sits comfortably above five. */ const MAX_TRANSITION_WALKBACK = 8; /** * Truncate a wall clock to the start of its `unit`. Pure wall-clock arithmetic. * * Calendar-aware: `local` keeps its calendar, so a Hebrew month or year truncates to the * Hebrew one. */ function truncateLocal(local, unit, weekStartsOn) { if (unit === "nanosecond") return local; if (needsCalendarCompat(local)) return truncateLocalWithCompat(local, unit, weekStartsOn); return truncateLocalInOwnCalendar(local, unit, weekStartsOn); } /** * CORE-6: true when `local`'s calendar arithmetic needs the Temporal compat layer in this runtime. * The polyfill's `with`, `add` and `until` are then wrong or throw on its wall clocks (D1–D7), so * the walker builds calendar periods from corrected reads and does everything else in ISO. */ function needsCalendarCompat(local) { return local.calendarId !== "iso8601" && isCalendarArithmeticCompatNeeded(local.calendarId); } function isCalendarPeriod(unit) { return unit === "year" || unit === "quarter" || unit === "month"; } /** `truncateLocal` for a calendar that needs the compat layer. */ function truncateLocalWithCompat(local, unit, weekStartsOn) { if (isCalendarPeriod(unit)) { const { year, month } = calendarFieldsOf(local.toPlainDate(), local.calendarId); const startMonth = unit === "year" ? 1 : unit === "quarter" ? quarterStartMonth(month) : month; return calendarDateFromFields(local.calendarId, { year, month: startMonth, day: 1 }, "reject").toPlainDateTime(); } return truncateLocalInOwnCalendar(local.withCalendar("iso8601"), unit, weekStartsOn).withCalendar(local.calendarId); } /** The first month of the quarter holding ordinal `month` (1, 4, 7 or 10). */ function quarterStartMonth(month) { return Math.floor((month - 1) / 3) * 3 + 1; } /** `truncateLocal` through `local`'s own calendar operations. */ function truncateLocalInOwnCalendar(local, unit, weekStartsOn) { if (unit === "nanosecond") return local; if (unit === "quarter") return local.with({ month: Math.floor((local.month - 1) / 3) * 3 + 1, day: 1, ...MIDNIGHT }); if (unit === "week") return local.subtract({ days: (local.dayOfWeek - weekStartsOn + 7) % 7 }).with(MIDNIGHT); return local.with(FIELDS_RESET_BY_UNIT[unit]); } /** The local `unit` label `zoned` carries — what the wall clock read, with no zone opinion. */ function localUnitLabel(zoned, unit, weekStartsOn) { return truncateLocal(zoned.toPlainDateTime(), unit, weekStartsOn).toString(); } /** `instant` in `like`'s zone and calendar. `toZonedDateTimeISO` alone would drop the calendar. */ function inZoneOf(instant, like) { return instant.toZonedDateTimeISO(like.timeZoneId).withCalendar(like.calendarId); } /** * The `unit` boundary reached from `zoned` without leaving its own offset stretch. * * The wall clock says how far into the unit `zoned` sits; that distance is then subtracted as * exact time, so the result keeps `zoned`'s offset instead of being re-resolved — which is * what stops a repeated wall time from being answered with the wrong pass of it. */ function boundaryInOwnOffset(zoned, unit, weekStartsOn) { const local = zoned.toPlainDateTime(); const elapsed = wallClockUntil(truncateLocal(local, unit, weekStartsOn), local, "hour"); return inZoneOf(zoned.toInstant().subtract(elapsed), zoned); } /** * `from.until(to, { largestUnit })` between two wall clocks in one calendar. Hours and smaller * never depend on the calendar, so a calendar that needs the compat layer measures them in ISO. */ function wallClockUntil(from, to, largestUnit) { return needsCalendarCompat(from) ? from.withCalendar("iso8601").until(to.withCalendar("iso8601"), { largestUnit }) : from.until(to, { largestUnit }); } /** * `from.until(to, { largestUnit: unit })` between two wall clocks already truncated to `unit`. A * calendar that needs the compat layer counts years and months with `calendarDateUntil` between * the dates (both clocks sit at midnight on a period start) and every other unit in ISO. */ function truncatedWallClockUntil(from, to, unit) { if (!needsCalendarCompat(from)) return from.until(to, { largestUnit: unit }); if (unit === "year" || unit === "month") return Temporal.Duration.from(calendarDateUntil(from.toPlainDate(), to.toPlainDate(), unit)); return from.withCalendar("iso8601").until(to.withCalendar("iso8601"), { largestUnit: unit }); } /** * The most recent zone transition at or before `zoned`, or null if there is none. * * `getTimeZoneTransition("previous")` is strict, so a transition sitting exactly on `zoned` is * missed by asking from `zoned` itself. Asking from a nanosecond later would find it, but throws at * the last representable instant, so this never steps past `zoned`: the first transition after * `zoned - 1 ns` is `zoned` itself exactly when a transition sits on it. At the first * representable instant there is no `zoned - 1 ns`, and nothing earlier, so that check is skipped. */ function transitionAtOrBefore(zoned, notBefore) { try { if (transitionSitsOn(zoned)) return zoned; return zonedPreviousTransition(zoned, notBefore.epochNanoseconds - 1n); } catch { return null; } } /** True when a zone transition happens exactly at `zoned`'s instant. */ function transitionSitsOn(zoned) { let justBefore; try { justBefore = zoned.subtract({ nanoseconds: 1 }); } catch { return false; } const next = zonedNextTransition(justBefore, zoned.epochNanoseconds); return next !== null && next.toInstant().equals(zoned.toInstant()); } /** Units whose buckets are labelled by a local date: a repeated wall time inside one stays one bucket. */ const DATE_LABELLED_UNITS = /* @__PURE__ */ new Set([ "year", "quarter", "month", "week", "day" ]); /** * True when the local `unit` bucket restarts at `transition` rather than continuing through it. * * - **The label changes discontinuously** — every unit. `Pacific/Chatham` jumps 02:45 → 03:45, * so the 03:00 hour begins at the transition even though the clock does not read 03:00:00; a * local day whose midnight is skipped begins at 01:00 the same way; and `America/Goose_Bay`'s * 2010-11-07 fall-back re-enters 6 November, so that 59-minute stretch is its own day. * - **The clock lands on a unit boundary** — hours and smaller only. London goes back to * 01:00:00 exactly, so a second, separate 01:00 hour begins there — which is why a fall-back * day has 25 hour buckets. `Australia/Lord_Howe` goes back to 01:30, mid-hour, so the hour it * is already in simply runs longer: 90 minutes. * - **Day and larger never reopen on the same label.** `America/Havana` fell back 01:00 → 00:00 * on 2024-11-03: the clock lands on midnight, but the date is still 3 November, so that is one * 25-hour day starting at the first 00:00 — matching Temporal's `startOfDay()` and `hoursInDay`. */ function startsNewBucketAt(transition, unit, weekStartsOn) { const local = transition.toPlainDateTime(); if (!DATE_LABELLED_UNITS.has(unit) && truncateLocal(local, unit, weekStartsOn).equals(local)) return true; try { return localUnitLabel(transition.subtract({ nanoseconds: 1 }), unit, weekStartsOn) !== localUnitLabel(transition, unit, weekStartsOn); } catch { return true; } } /** * Return the instant the local `unit` containing `zoned` began — the bucket `zoned` falls in. * * A bucket is the run of instants sharing `zoned`'s local label *without interruption*, so * this walks back from `zoned` to where that run started. Re-resolving a truncated wall clock * cannot do the job, because truncation can land on a local time the zone never had and * Temporal's "compatible" disambiguation then relocates it: * * - **A gap pushes the boundary past the instant being floored.** `Pacific/Chatham` springs * forward 02:45 → 03:45, so local 03:00 never happens; truncating 03:45 to the hour and * resolving it lands fifteen minutes *after* the instant it was asked to floor. * `Antarctica/Casey`'s three-hour 2020 jump lands three hours after. * - **A sub-hour fall-back answers with the wrong pass.** Chatham falls back 03:45 → 02:45, * so local 02:00 and local 03:00 each name two instants an hour and three quarters apart, * and "compatible" always picks the earlier — silently skipping a boundary. * * So the boundary is taken in `zoned`'s own offset, then extended back through any transition * the bucket runs straight through. See `startsNewBucketAt` for which those are. * * - Handles every `DateTimeUnit` plus `quarter`. Sub-hour units need the same own-offset treatment, because * historic offsets carry seconds (`Africa/Monrovia` ran at −00:44:30 until 1972). * - Weeks start on `weekStartsOn` (ISO day number, Monday by default). * - Keeps `zoned`'s calendar, so a non-ISO month or year floors in that calendar. * - Returns null if the walk-back is still inside transitions after `MAX_TRANSITION_WALKBACK` * of them, which no IANA zone comes close to. The last `start` reached at that point is * only a partial answer, and a bounded walk that runs out answers with the sentinel. */ function zonedUnitStart(zoned, unit, weekStartsOn = 1) { let start = boundaryInOwnOffset(zoned, unit, weekStartsOn); let cursor = zoned; for (let i = 0; i < MAX_TRANSITION_WALKBACK; i++) { const transition = transitionAtOrBefore(cursor, start); if (!transition || Temporal.ZonedDateTime.compare(transition, start) < 0) return start; if (startsNewBucketAt(transition, unit, weekStartsOn)) return transition; const justBefore = transition.subtract({ nanoseconds: 1 }); start = boundaryInOwnOffset(justBefore, unit, weekStartsOn); cursor = justBefore; } return null; } /** * The next `unit` boundary after `zoned`, reached without leaving its own offset stretch. */ function nextBoundaryInOwnOffset(zoned, unit, weekStartsOn) { const local = zoned.toPlainDateTime(); const remaining = wallClockUntil(local, truncateLocal(addOneUnit(local, unit), unit, weekStartsOn), "hour"); return inZoneOf(zoned.toInstant().add(remaining), zoned); } /** * `nextBoundaryInOwnOffset`, or null when that boundary lies past Temporal's last representable * instant — a transition before it may still open a representable bucket. */ function nextBoundaryWithinRange(zoned, unit, weekStartsOn) { try { return nextBoundaryInOwnOffset(zoned, unit, weekStartsOn); } catch (error) { if (error instanceof RangeError) return null; throw error; } } /** * `local.add(oneUnit(unit))`. For a calendar that needs the compat layer, a calendar period steps * through `calendarDateAdd` (constrained, keeping the time of day) and every other unit in ISO. */ function addOneUnit(local, unit) { if (!needsCalendarCompat(local)) return local.add(oneUnit(unit)); if (isCalendarPeriod(unit)) return calendarDateAdd(local.toPlainDate(), unit === "year" ? { years: 1 } : { months: unit === "quarter" ? 3 : 1 }, "constrain").toPlainDateTime(local.toPlainTime()); return local.withCalendar("iso8601").add(oneUnit(unit)).withCalendar(local.calendarId); } /** * Return the start of the bucket following the one containing `current` (which need not be that * bucket's start). * * Stepping a whole unit and re-flooring is wrong, because a bucket can be shorter than its * unit and would be stepped straight over: `Pacific/Chatham`'s 02:45 → 03:45 spring-forward * leaves a local 03:00 hour only fifteen minutes long. So this takes whichever comes first — * the next boundary in the current offset, or a transition that opens a bucket of its own — * and runs through any transition that does not. * * - Handles every `DateTimeUnit` plus `quarter`, weeks starting on `weekStartsOn` (Monday by default). * - Returns null if neither is reachable within `MAX_TRANSITION_WALKBACK` transitions, which * no IANA zone comes close to. * - Throws a RangeError when the next bucket starts after the last representable instant. */ function nextZonedBucketStart(current, unit, weekStartsOn = 1) { let cursor = current; for (let i = 0; i < MAX_TRANSITION_WALKBACK; i++) { const boundary = nextBoundaryWithinRange(cursor, unit, weekStartsOn); const transition = zonedNextTransition(cursor, boundary?.epochNanoseconds); if (!transition || boundary !== null && Temporal.ZonedDateTime.compare(transition, boundary) > 0) { if (boundary === null) throw new RangeError("the next bucket starts after the last representable instant"); return boundary; } if (startsNewBucketAt(transition, unit, weekStartsOn)) return transition.withCalendar(current.calendarId); cursor = transition.withCalendar(current.calendarId); } return null; } /** * Return the last instant of the local `unit` containing `zoned`: one nanosecond before the * next bucket starts. * * - Never earlier than `zoned`, because it is measured from the real bucket `zoned` is in — * London's second 01:00 hour on a fall-back morning ends at 01:59:59.999999999 +00:00, not * at the first pass's. * - Walks forward from `zoned` itself, never from its bucket's start. No transition between that * start and `zoned` opens a bucket, so both walks reach the same next start — but the start may * lie before the first representable instant (the month holding `-271821-04-20T00:00:00Z` began * on 1 April), while the end does not. * - Returns null if the next bucket start cannot be found. */ function zonedUnitEnd(zoned, unit, weekStartsOn = 1) { const next = nextZonedBucketStart(zoned, unit, weekStartsOn); return next ? next.subtract({ nanoseconds: 1 }) : null; } /** * `countZonedBuckets` when `start`'s bucket began before the first representable instant (the * week, month or year holding `-271821-04-20T00:00:00Z`). `start` is then inside that bucket, not * on its start, so the span touches it once, plus every bucket from the next start on. */ function countFromBucketBeforeRange(start, end, unit, weekStartsOn) { const next = nextZonedBucketStart(start, unit, weekStartsOn); if (!next) return null; if (Temporal.ZonedDateTime.compare(next, end) >= 0) return 1; const rest = countZonedBuckets(next, end, unit, weekStartsOn); return rest === null ? null : rest + 1; } /** Nanoseconds in each unit below a day. */ const SUB_DAY_NANOSECONDS = { hour: 3600000000000n, minute: 60000000000n, second: 1000000000n, millisecond: 1000000n, microsecond: 1000n, nanosecond: 1n }; /** * Which bucket a wall clock (nanoseconds, read as UTC) falls in, as an integer that rises by one * per bucket: the unit's count since the epoch, so a difference is the whole units between two * labels. Months and years are ISO; a calendar period of another calendar has no integer form. */ function bucketIndexOf(unit, weekStartsOn) { const fixed = SUB_DAY_NANOSECONDS[unit]; if (fixed !== void 0) return (wall) => floorDivide(wall, fixed); if (unit === "day") return (wall) => floorDivide(wall, NANOSECONDS_PER_DAY); if (unit === "week") { const anchor = -((isoWeekdayOf(0) - weekStartsOn + 7) % 7); return (wall) => { const day = Number(floorDivide(wall, NANOSECONDS_PER_DAY)); const weekStart = day - (isoWeekdayOf(day) - weekStartsOn + 7) % 7; return BigInt((weekStart - anchor) / 7); }; } return (wall) => { const [year, month] = isoFieldsOf(Number(floorDivide(wall, NANOSECONDS_PER_DAY))); return BigInt(unit === "year" ? year : year * 12 + month - 1); }; } /** * The two questions `countZonedBuckets` asks of an offset change, in integers where the unit * allows: whether a change opens a bucket (`startsNewBucketAt`'s rule), and how many whole units * lie between the buckets two instants fall in. A month or year of a non-ISO calendar asks * Temporal, and only at a change that crosses a date. */ function bucketWalker(start, unit, weekStartsOn) { const sinceMidnight = (wall) => floorDivide(wall, NANOSECONDS_PER_DAY); if (start.calendarId !== "iso8601" && (unit === "month" || unit === "year")) { const zonedAt = (ns) => new Temporal.ZonedDateTime(ns, start.timeZoneId, start.calendarId); const label = (ns) => truncateLocal(zonedAt(ns).toPlainDateTime(), unit, weekStartsOn); return { opensBucket: (transition, before, after) => sinceMidnight(transition - 1n + before) !== sinceMidnight(transition + after) && startsNewBucketAt(zonedAt(transition), unit, weekStartsOn), unitsBetween: (fromNs, _fromOffset, toNs) => getUnitSpan(truncatedWallClockUntil(label(fromNs), label(toNs), unit), unit) }; } const index = bucketIndexOf(unit, weekStartsOn); const length = SUB_DAY_NANOSECONDS[unit]; return { opensBucket: (transition, before, after) => index(transition - 1n + before) !== index(transition + after) || length !== void 0 && (transition + after) % length === 0n, unitsBetween: (fromNs, fromOffset, toNs, toOffset) => Number(index(toNs + toOffset) - index(fromNs + fromOffset)) }; } /** * Count the local `unit` buckets the half-open interval `[start, end)` touches, in `start`'s * zone and calendar. `end` must already be expressed in both. * * The count is the bucket `start` is in, plus every bucket that starts after it and at or * before `end` — less one when `end` sits exactly on a bucket start, since the interval does * not reach into that bucket. A calendar-unit difference between truncated endpoints gets * transitions wrong both ways: Chatham's 15-minute 03:00 hour is a bucket the difference * never sees, and Samoa's deleted 2011-12-30 is a day the difference counts anyway. * * - Between transitions the wall clock runs continuously, so buckets there are counted by the * whole-unit difference of their local labels. * - A transition that does not open a bucket (see `startsNewBucketAt`) leaves the label * running on, so it changes nothing and is stepped over. * - A transition that does open one closes the run before it and counts the new bucket. * - A `start` whose bucket began before the first representable instant still counts that * bucket once. * - Returns null if either endpoint's bucket cannot be found, or the span crosses more than * `MAX_COUNTED_TRANSITIONS` transitions. */ function countZonedBuckets(start, end, unit, weekStartsOn = 1) { let startOfStart; try { startOfStart = zonedUnitStart(start, unit, weekStartsOn); } catch (error) { if (!(error instanceof RangeError)) throw error; return countFromBucketBeforeRange(start, end, unit, weekStartsOn); } const startOfEnd = zonedUnitStart(end, unit, weekStartsOn); if (!startOfStart || !startOfEnd) return null; const timeline = offsetTimeline({ timeZone: start.timeZoneId, shiftNanoseconds: 0n }, startOfStart.epochNanoseconds, startOfEnd.epochNanoseconds, 9999); if (timeline === null) return null; const { changes, offsets } = timeline; const walker = bucketWalker(start, unit, weekStartsOn); const endNs = startOfEnd.epochNanoseconds; const reachesIntoEndBucket = startOfEnd.epochNanoseconds === end.epochNanoseconds ? 0 : 1; let spanned = 0; let runStart = startOfStart.epochNanoseconds; let runStartOffset = offsets[0]; let runOffset = offsets[0]; for (let index = 0; index < changes.length; index++) { const transition = changes[index]; const after = offsets[index + 1]; if (walker.opensBucket(transition, runOffset, after)) { spanned += walker.unitsBetween(runStart, runStartOffset, transition - 1n, runOffset) + 1; runStart = transition; runStartOffset = after; } runOffset = after; } return spanned + walker.unitsBetween(runStart, runStartOffset, endNs, runOffset) + reachesIntoEndBucket; } export { countZonedBuckets, nextZonedBucketStart, zonedUnitEnd, zonedUnitStart };