@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.
147 lines (145 loc) • 8.53 kB
JavaScript
import { Temporal } from "./temporal.js";
import { isCalendarArithmeticCompatNeeded, isNudgeWindowCompatNeeded } from "./temporalCompat/capabilities.js";
import { timeZoneEquals } from "./temporalCompat/timeZoneEquals.js";
import { isObject } from "./isObject.js";
import { zonedDateTimeFrom } from "./zonedWallClock.js";
import { compareAtLimit, defaultLargestUnit, isDateUnit, largerUnit, roundAtLimit, roundingSettings, timeZoneAnnotation, toUnit, totalAtLimit, untilAtLimit } from "./zonedDifference/operations.js";
import { UNIT_REACH, durationReach, reachesRangeLimit, roundingReach, runAtRangeLimit } from "./zonedDifference/rangeLimit.js";
import { calendarCompareBySpec, calendarRoundBySpec, calendarTotalBySpec, plainDateUntilWithRounding } from "./zonedDifference/calendarArithmetic.js";
import { originNeedsSpecPath, originRoundBySpec, originTotalBySpec } from "./zonedDifference/nudgeOrigin.js";
import { isNudgeWindowUnit, monthRoundBySpec, monthTotalBySpec, plainUntilWithRounding } from "./zonedDifference/nudgeWindow.js";
// src/internal/zonedWallClockDifference.ts
function inTimeZone(zoned, timeZone) {
return zoned.timeZoneId === timeZone ? zoned : zoned.withTimeZone(timeZone);
}
/** The zoned `relativeTo` Temporal would resolve, or null when it is not zoned. */
function zonedRelativeTo(relativeTo) {
if (relativeTo instanceof Temporal.ZonedDateTime) return relativeTo;
try {
if (typeof relativeTo === "string") return timeZoneAnnotation.test(relativeTo) ? zonedDateTimeFrom(relativeTo) : null;
if (isObject(relativeTo) && !(relativeTo instanceof Temporal.PlainDateTime) && "timeZone" in relativeTo && relativeTo.timeZone !== void 0) return zonedDateTimeFrom(relativeTo);
} catch {}
return null;
}
const CALENDAR_DIFFERENCE_UNITS = /* @__PURE__ */ new Set([
"year",
"years",
"month",
"months",
"week",
"weeks",
"day",
"days"
]);
/**
* Whether Temporal's DifferenceTemporalZonedDateTime would reject `largestUnit` for this pair: a
* calendar unit (day or larger) between two different time zones (TimeZoneEquals is false), because
* "day lengths can vary between time zones due to DST". TimeZoneEquals compares primary
* identifiers, so `UTC` equals `Etc/UTC` and `Asia/Calcutta` equals `Asia/Kolkata`
* (`timeZoneEquals`, temporalCompat D19).
*
* @param one the start
* @param two the end
* @param largestUnit the requested `largestUnit`
* @returns true when the pair cannot be differenced in `largestUnit`
*/
function isCalendarDifferenceAcrossZones(one, two, largestUnit) {
if (!CALENDAR_DIFFERENCE_UNITS.has(largestUnit)) return false;
return !timeZoneEquals(one, two);
}
/**
* `ZonedDateTime#until`, correct at the range limits (see the note at the top of this file).
*
* @param one the start
* @param two the end
* @param options Temporal `largestUnit` / `smallestUnit` / `roundingIncrement` / `roundingMode`
* @returns the difference; throws where TC39 Temporal throws for the rounding options. A calendar
* `largestUnit` across two time zones is not rejected here (TC39 DifferenceTemporalZonedDateTime
* throws a RangeError): callers gate it with `isCalendarDifferenceAcrossZones`.
*/
function zonedUntil(one, two, options = {}) {
const settings = roundingSettings(options.largestUnit, options.smallestUnit, (smallestUnit) => largerUnit("hour", smallestUnit), options.roundingIncrement, options.roundingMode ?? "trunc");
let sameZone;
const inSameZone = () => sameZone ??= timeZoneEquals(one, two);
if (settings !== null && untilTakesSpecPath(one, two, settings) && inSameZone()) {
const bySpec = untilAtLimit(one, two, options, settings);
if (bySpec !== null) return bySpec;
}
const atRangeLimit = settings !== null && reachesRangeLimit([one.epochNanoseconds, two.epochNanoseconds], roundingReach(settings)) && inSameZone();
return runAtRangeLimit(one.timeZoneId, atRangeLimit, (timeZone) => inTimeZone(one, timeZone).until(inTimeZone(two, timeZone), options), () => untilAtLimit(one, two, options, settings));
}
/**
* True when `until` must take the spec path because the polyfill would answer wrongly, not throw.
*
* Defect 3: a calendar whose arithmetic the polyfill gets wrong (D6 is a wrong month end). Defect 4:
* a calendar `smallestUnit` from a day that a month add would constrain. Defect 5
* (`./zonedDifference/nudgeOrigin.ts`): a date `largestUnit` the runtime would mismeasure, or for
* which the specification has no value. The last of the three terms to go takes this function with
* it, along with the `// defects 3–5` block in `zonedUntil`.
*/
function untilTakesSpecPath(one, two, settings) {
return one.calendarId === two.calendarId && (isCalendarArithmeticCompatNeeded(one.calendarId) || isNudgeWindowUnit(settings.smallestUnit) && one.day >= 29 && isNudgeWindowCompatNeeded() || isDateUnit(settings.largestUnit) && originNeedsSpecPath(one, two.epochNanoseconds));
}
/**
* `Duration#total({ unit, relativeTo })`, correct at the range limits and in calendars the
* polyfill gets wrong.
*
* @param duration the duration to total
* @param unit the Temporal unit to total in
* @param relativeTo Temporal `relativeTo`; a zoned one reaches the range-limit fallbacks, and a
* zoned or plain one in a calendar that needs the compat layer takes the spec path
* @returns the total; throws where TC39 Temporal throws
*/
function durationTotal(duration, unit, relativeTo) {
const zoned = zonedRelativeTo(relativeTo);
const resolvedUnit = toUnit(unit);
const bySpec = resolvedUnit === null ? null : calendarTotalBySpec(duration, unit, resolvedUnit, relativeTo, zoned) ?? monthTotalBySpec(duration, unit, resolvedUnit, relativeTo, zoned) ?? originTotalBySpec(duration, unit, resolvedUnit, zoned);
if (bySpec !== null) return bySpec;
if (zoned === null) return duration.total({
unit,
relativeTo
});
const atRangeLimit = resolvedUnit !== null && reachesRangeLimit([zoned.epochNanoseconds], durationReach(duration) + UNIT_REACH[resolvedUnit]);
return runAtRangeLimit(zoned.timeZoneId, atRangeLimit, (timeZone) => duration.total({
unit,
relativeTo: inTimeZone(zoned, timeZone)
}), () => totalAtLimit(duration, zoned, unit, resolvedUnit));
}
/**
* `Duration#round(roundTo)`, correct at the range limits.
*
* @param duration the duration to round
* @param roundTo Temporal round options; only a zoned `relativeTo` reaches the fallbacks
* @returns the rounded duration; throws where TC39 Temporal throws
*/
function durationRound(duration, roundTo) {
const zoned = zonedRelativeTo(roundTo.relativeTo);
const settings = roundingSettings(roundTo.largestUnit, roundTo.smallestUnit, (smallestUnit) => largerUnit(defaultLargestUnit(duration), smallestUnit), roundTo.roundingIncrement, roundTo.roundingMode ?? "halfExpand");
const bySpec = settings === null ? null : calendarRoundBySpec(duration, roundTo, settings, zoned) ?? monthRoundBySpec(duration, roundTo, settings, zoned) ?? originRoundBySpec(duration, roundTo, settings, zoned);
if (bySpec !== null) return bySpec;
if (zoned === null) return duration.round(roundTo);
const atRangeLimit = settings !== null && reachesRangeLimit([zoned.epochNanoseconds], durationReach(duration) + roundingReach(settings));
return runAtRangeLimit(zoned.timeZoneId, atRangeLimit, (timeZone) => duration.round({
...roundTo,
relativeTo: inTimeZone(zoned, timeZone)
}), () => roundAtLimit(duration, zoned, roundTo, settings));
}
/**
* `Temporal.Duration.compare(one, two, { relativeTo })`, correct at the range limits.
*
* @param one the first duration
* @param two the second duration
* @param relativeTo Temporal `relativeTo`; only a zoned one reaches the fallbacks
* @returns -1, 0 or 1; throws where TC39 Temporal throws
*/
function durationCompare(one, two, relativeTo) {
const zoned = zonedRelativeTo(relativeTo);
const bySpec = calendarCompareBySpec(one, two, relativeTo, zoned);
if (bySpec !== null) return bySpec;
if (zoned === null) return Temporal.Duration.compare(one, two, { relativeTo });
const first = Temporal.Duration.from(one);
const second = Temporal.Duration.from(two);
const reach = durationReach(first) > durationReach(second) ? durationReach(first) : durationReach(second);
return runAtRangeLimit(zoned.timeZoneId, reachesRangeLimit([zoned.epochNanoseconds], reach), (timeZone) => Temporal.Duration.compare(first, second, { relativeTo: inTimeZone(zoned, timeZone) }), () => compareAtLimit(first, second, zoned));
}
export { durationCompare, durationRound, durationTotal, isCalendarDifferenceAcrossZones, plainDateUntilWithRounding, plainUntilWithRounding, zonedUntil };