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.

613 lines (611 loc) • 28.4 kB
import { Temporal } from "../temporal.js"; import { TIME_ZONE_ANNOTATION } from "../isoStringBody.js"; import { MAX_EPOCH_NANOSECONDS, MIN_EPOCH_NANOSECONDS } from "../epochNanoseconds.js"; import { calendarDateAdd as calendarDateAdd$1, calendarDateUntil as calendarDateUntil$1 } from "../temporalCompat/calendarDateArithmetic.js"; import { epochNanosecondsFor, isValidEpoch, utcEpochNanoseconds } from "../zonedWallClock.js"; // src/internal/zonedDifference/operations.ts const UNITS = [ "year", "month", "week", "day", "hour", "minute", "second", "millisecond", "microsecond", "nanosecond" ]; const NANOSECONDS_PER_HOUR = 3600000000000n; const NANOSECONDS_PER_DAY = 24n * NANOSECONDS_PER_HOUR; /** TC39 Table "Temporal units by descending magnitude", "Length in Nanoseconds" column. */ const NANOSECONDS_PER_TIME_UNIT = { hour: NANOSECONDS_PER_HOUR, minute: 60000000000n, second: 1000000000n, millisecond: 1000000n, microsecond: 1000n, nanosecond: 1n }; /** TC39 `maxTimeDuration`: 2^53 × 10^9 − 1 nanoseconds. */ const MAX_TIME_DURATION = 2n ** 53n * 1000000000n - 1n; /** Validates Temporal options exactly as the wrapped method does, far from any limit. */ const OPTIONS_PROBE = new Temporal.ZonedDateTime(0n, "UTC"); const ZERO_DURATION = new Temporal.Duration(); /** An RFC 9557 time zone annotation (`[Europe/London]`, `[!+01:00]`), never a `key=value` one. */ const timeZoneAnnotation = new RegExp(TIME_ZONE_ANNOTATION); const ZERO_DATE_DURATION = { years: 0, months: 0, weeks: 0, days: 0 }; /** A Temporal unit name, singular or plural, or null when it is not one. */ function toUnit(value) { if (typeof value !== "string") return null; const singular = value.endsWith("s") ? value.slice(0, -1) : value; return UNITS.find((unit) => unit === singular) ?? null; } /** TC39 `TemporalUnitCategory(unit)` is ~date~. */ function isDateUnit(unit) { return UNITS.indexOf(unit) <= UNITS.indexOf("day"); } /** TC39 `LargerOfTwoTemporalUnits`. */ function largerUnit(one, two) { return UNITS.indexOf(one) <= UNITS.indexOf(two) ? one : two; } function bigintSign(value) { if (value < 0n) return -1; return value > 0n ? 1 : 0; } function bigintAbs(value) { return value < 0n ? -value : value; } /** TC39 `DateDurationSign`. */ function dateDurationSign(duration) { for (const value of [ duration.years, duration.months, duration.weeks, duration.days ]) if (value !== 0) return value < 0 ? -1 : 1; return 0; } /** TC39 `InternalDurationSign`. */ function internalDurationSign(duration) { return dateDurationSign(duration.date) || bigintSign(duration.time); } /** TC39 `AdjustDateDurationRecord`. */ function adjustDateDuration(duration, days, weeks = duration.weeks, months = duration.months) { return { years: duration.years, months, weeks, days }; } /** TC39 `ToInternalDurationRecord`. */ function toInternalDuration(duration) { const { years, months, weeks, days } = duration; return { date: { years, months, weeks, days }, time: BigInt(duration.hours) * NANOSECONDS_PER_TIME_UNIT.hour + BigInt(duration.minutes) * NANOSECONDS_PER_TIME_UNIT.minute + BigInt(duration.seconds) * NANOSECONDS_PER_TIME_UNIT.second + BigInt(duration.milliseconds) * NANOSECONDS_PER_TIME_UNIT.millisecond + BigInt(duration.microseconds) * NANOSECONDS_PER_TIME_UNIT.microsecond + BigInt(duration.nanoseconds) }; } /** TC39 `DefaultTemporalLargestUnit`. */ function defaultLargestUnit(duration) { return UNITS.find((unit) => duration[`${unit}s`] !== 0) ?? "nanosecond"; } /** TC39 `GetUnsignedRoundingMode`, as [positive, negative]. */ const UNSIGNED_ROUNDING_MODES = { ceil: ["infinity", "zero"], floor: ["zero", "infinity"], expand: ["infinity", "infinity"], trunc: ["zero", "zero"], halfCeil: ["half-infinity", "half-zero"], halfFloor: ["half-zero", "half-infinity"], halfExpand: ["half-infinity", "half-infinity"], halfTrunc: ["half-zero", "half-zero"], halfEven: ["half-even", "half-even"] }; function unsignedRoundingMode(roundingMode, sign) { return UNSIGNED_ROUNDING_MODES[roundingMode][sign < 0 ? 1 : 0]; } /** TC39 `ApplyUnsignedRoundingMode`, given the sign of (2 × remainder − increment) as `cmp`. */ function applyUnsignedRoundingMode(r1, r2, cmp, even, mode) { if (mode === "zero") return r1; if (mode === "infinity") return r2; if (cmp !== 0) return cmp < 0 ? r1 : r2; if (mode === "half-zero") return r1; if (mode === "half-infinity") return r2; return even ? r1 : r2; } /** TC39 `RoundTimeDurationToIncrement`. */ function roundTimeDurationToIncrement(duration, increment, roundingMode) { const quotient = bigintAbs(duration / increment); const remainder = duration % increment; const r1 = quotient * increment; const rounded = remainder === 0n ? r1 : applyUnsignedRoundingMode(r1, r1 + increment, bigintSign(bigintAbs(remainder * 2n) - increment), quotient % 2n === 0n, unsignedRoundingMode(roundingMode, bigintSign(duration))); const result = duration < 0n ? -rounded : rounded; if (bigintAbs(result) > MAX_TIME_DURATION) throw new RangeError("The rounded time duration is out of range"); return result; } /** * The float64 value of `numerator / denominator`, as the polyfill's `TimeDuration#fdiv` computes * TC39's exact division: the integer quotient plus 50 long-division decimal digits. */ function divideToNumber(numerator, denominator) { const divisor = bigintAbs(denominator); let remainder = bigintAbs(numerator % denominator); const digits = []; while (remainder !== 0n && digits.length < 50) { remainder *= 10n; digits.push(String(remainder / divisor)); remainder %= divisor; } const magnitude = Number(`${bigintAbs(numerator / denominator)}.${digits.join("")}`); return bigintSign(numerator) * bigintSign(denominator) < 0 ? -magnitude : magnitude; } /** TC39 `GetISODateTimeFor`. */ function isoDateTimeFor(timeZone, epochNs) { return new Temporal.ZonedDateTime(epochNs, timeZone).toPlainDateTime(); } /** TC39 `GetEpochNanosecondsFor(timeZone, isoDateTime, ~compatible~)` for a named zone. */ function epochFor(timeZone, wall) { return epochNanosecondsFor(timeZone, wall, "compatible"); } /** * TC39 `CombineISODateAndTimeRecord`. A combination outside the PlainDateTime limits throws here; * the spec throws for it at the `GetEpochNanosecondsFor` that always follows. */ function atTimeOf(date, wall) { return date.toPlainDateTime(wall.toPlainTime()); } /** * TC39 `CalendarDateAdd(calendar, isoDate, duration, ~constrain~)`, through the Temporal compat * layer (the polyfill's own `add` for `iso8601`). */ function calendarDateAdd(calendar, isoDate, duration) { return calendarDateAdd$1(isoDate.withCalendar(calendar), duration, "constrain").withCalendar("iso8601"); } /** TC39 `CalendarDateUntil`, through the Temporal compat layer. */ function calendarDateUntil(calendar, one, two, largestUnit) { return calendarDateUntil$1(one.withCalendar(calendar), two.withCalendar(calendar), largestUnit); } /** TC39 `AddInstant`. */ function addInstant(epochNs, time) { const result = epochNs + time; if (!isValidEpoch(result)) throw new RangeError("The result is outside the supported range"); return result; } /** TC39 `AddZonedDateTime(…, ~constrain~)`. */ function addZonedDateTime(zoned, duration) { if (dateDurationSign(duration.date) === 0) return addInstant(zoned.epochNanoseconds, duration.time); const wall = isoDateTimeFor(zoned.timeZoneId, zoned.epochNanoseconds); const addedDate = calendarDateAdd(zoned.calendarId, wall.toPlainDate(), duration.date); return addInstant(epochFor(zoned.timeZoneId, atTimeOf(addedDate, wall)), duration.time); } /** TC39 `TemporalDurationFromInternal` for a time `largestUnit`, balanced by `Instant#until`. */ function temporalDurationFromInternal(duration, largestUnit) { const base = duration.time < 0n ? MAX_EPOCH_NANOSECONDS : MIN_EPOCH_NANOSECONDS; const time = new Temporal.Instant(base).until(new Temporal.Instant(base + duration.time), { largestUnit }); const { years, months, weeks, days } = duration.date; return new Temporal.Duration(years, months, weeks, days, time.hours, time.minutes, time.seconds, time.milliseconds, time.microseconds, time.nanoseconds); } /** TC39 `DifferenceZonedDateTime`. */ function differenceZonedDateTime(ns1, ns2, context, largestUnit) { if (ns1 === ns2) return { date: ZERO_DATE_DURATION, time: 0n }; const start = isoDateTimeFor(context.timeZone, ns1); const end = isoDateTimeFor(context.timeZone, ns2); const startDate = start.toPlainDate(); const endDate = end.toPlainDate(); if (Temporal.PlainDate.compare(startDate, endDate) === 0) return { date: ZERO_DATE_DURATION, time: ns2 - ns1 }; const sign = ns2 - ns1 < 0n ? 1 : -1; const maxDayCorrection = sign === -1 ? 2 : 1; let dayCorrection = Temporal.PlainTime.compare(end.toPlainTime(), start.toPlainTime()) === sign ? 1 : 0; for (; dayCorrection <= maxDayCorrection; dayCorrection++) { const intermediate = atTimeOf(endDate.add({ days: dayCorrection * sign }), start); const time = ns2 - epochFor(context.timeZone, intermediate); if (bigintSign(time) !== sign) return combineDateAndTimeDuration(calendarDateUntil(context.calendar, startDate, intermediate.toPlainDate(), largerUnit(largestUnit, "day")), time); } throw new RangeError("More than the maximum day correction was needed"); } /** * TC39 `CombineDateAndTimeDuration`. Its Assert fails when the two signs disagree, which a repeated * hour spanning midnight causes: 15 minutes after `1944-10-01T00:00:59-06:00` in America/Phoenix * reads `1944-09-30T23:15:59-07:00`. The specification has no value there, so this throws and the * public function returns its sentinel (defect 5, tc39/proposal-temporal#3311). */ function combineDateAndTimeDuration(date, time) { if (dateDurationSign(date) * bigintSign(time) < 0) throw new RangeError("The date and time signs disagree"); return { date, time }; } function truncateToIncrement(value, increment) { return Math.trunc(value / increment) * increment; } /** The [[R1]]/[[R2]] bounds and their date durations, from TC39 `ComputeNudgeWindow` steps 1–4. */ function nudgeWindowBounds(sign, date, context, increment, unit, additionalShift) { const shift = additionalShift ? increment * sign : 0; if (unit === "year") { const r1 = truncateToIncrement(date.years, increment) + shift; const r2 = r1 + increment * sign; return { r1, r2, startDuration: { ...ZERO_DATE_DURATION, years: r1 }, endDuration: { ...ZERO_DATE_DURATION, years: r2 } }; } if (unit === "month") { const r1 = truncateToIncrement(date.months, increment) + shift; const r2 = r1 + increment * sign; return { r1, r2, startDuration: adjustDateDuration(date, 0, 0, r1), endDuration: adjustDateDuration(date, 0, 0, r2) }; } if (unit === "week") { const weeksStart = calendarDateAdd(context.calendar, context.wall.toPlainDate(), adjustDateDuration(date, 0, 0)); const weeksEnd = weeksStart.add({ days: date.days }); const untilResult = calendarDateUntil(context.calendar, weeksStart, weeksEnd, "week"); const r1 = truncateToIncrement(date.weeks + untilResult.weeks, increment); const r2 = r1 + increment * sign; return { r1, r2, startDuration: adjustDateDuration(date, 0, r1), endDuration: adjustDateDuration(date, 0, r2) }; } const r1 = truncateToIncrement(date.days, increment); const r2 = r1 + increment * sign; return { r1, r2, startDuration: adjustDateDuration(date, r1), endDuration: adjustDateDuration(date, r2) }; } /** The exact time `duration` after the origin wall clock, resolved in the zone. */ function windowBoundEpoch(context, duration) { return contextEpoch(context, atTimeOf(calendarDateAdd(context.calendar, context.wall.toPlainDate(), duration), context.wall)); } /** * The exact time of `wall` in `context`: TC39 `GetEpochNanosecondsFor(timeZone, wall, ~compatible~)`, * or `GetUTCEpochNanoseconds(wall)` when the time zone is unset (a plain context). */ function contextEpoch(context, wall) { return context.timeZone === void 0 ? utcEpochNanoseconds(wall) : epochFor(context.timeZone, wall); } /** TC39 `ComputeNudgeWindow`. */ function computeNudgeWindow(sign, duration, originEpochNs, context, increment, unit, additionalShift) { const bounds = nudgeWindowBounds(sign, duration.date, context, increment, unit, additionalShift); const startEpochNs = dateDurationSign(bounds.startDuration) === 0 ? originEpochNs : windowBoundEpoch(context, bounds.startDuration); return { ...bounds, startEpochNs, endEpochNs: windowBoundEpoch(context, bounds.endDuration) }; } function windowContains(sign, window, destEpochNs) { const [low, high] = sign === 1 ? [window.startEpochNs, window.endEpochNs] : [window.endEpochNs, window.startEpochNs]; return low <= destEpochNs && destEpochNs <= high; } /** TC39 `NudgeToCalendarUnit`; `total` is its [[Total]]. */ function nudgeToCalendarUnit(sign, duration, originEpochNs, destEpochNs, context, increment, unit, roundingMode) { let window = computeNudgeWindow(sign, duration, originEpochNs, context, increment, unit, false); let didExpandCalendarUnit = false; if (!windowContains(sign, window, destEpochNs)) { window = computeNudgeWindow(sign, duration, originEpochNs, context, increment, unit, true); if (!windowContains(sign, window, destEpochNs)) throw new RangeError("The target is outside the window"); didExpandCalendarUnit = true; } const { r1, r2, startEpochNs, endEpochNs } = window; const progress = destEpochNs - startEpochNs; const span = endEpochNs - startEpochNs; const total = divideToNumber(span * BigInt(r1) + progress * BigInt(sign), span); let roundedUnit; if (progress === 0n) roundedUnit = Math.abs(r1); else if (progress === span) roundedUnit = Math.abs(r2); else roundedUnit = applyUnsignedRoundingMode(Math.abs(r1), Math.abs(r2), bigintSign(bigintAbs(progress * 2n) - bigintAbs(span)), Math.abs(r1) / increment % 2 === 0, unsignedRoundingMode(roundingMode, sign)); const expanded = roundedUnit === Math.abs(r2); return { nudgeResult: { duration: { date: expanded ? window.endDuration : window.startDuration, time: 0n }, nudgedEpochNs: expanded ? endEpochNs : startEpochNs, didExpandCalendarUnit: didExpandCalendarUnit || expanded }, total }; } /** TC39 `NudgeToZonedTime`. */ function nudgeToZonedTime(sign, duration, context, increment, unit, roundingMode) { const start = calendarDateAdd(context.calendar, context.wall.toPlainDate(), duration.date); const startEpochNs = epochFor(context.timeZone, atTimeOf(start, context.wall)); const endEpochNs = epochFor(context.timeZone, atTimeOf(start.add({ days: sign }), context.wall)); const daySpan = endEpochNs - startEpochNs; if (bigintSign(daySpan) !== sign) throw new RangeError("The time zone returned inconsistent instants"); const unitIncrement = BigInt(increment) * NANOSECONDS_PER_TIME_UNIT[unit]; let roundedTime = roundTimeDurationToIncrement(duration.time, unitIncrement, roundingMode); const beyondDaySpan = roundedTime - daySpan; const didRoundBeyondDay = bigintSign(beyondDaySpan) !== -sign; let nudgedEpochNs = startEpochNs + roundedTime; if (didRoundBeyondDay) { roundedTime = roundTimeDurationToIncrement(beyondDaySpan, unitIncrement, roundingMode); nudgedEpochNs = endEpochNs + roundedTime; } return { duration: { date: adjustDateDuration(duration.date, duration.date.days + (didRoundBeyondDay ? sign : 0)), time: roundedTime }, nudgedEpochNs, didExpandCalendarUnit: didRoundBeyondDay }; } /** The date duration one `unit` further than `date`, per TC39 `BubbleRelativeDuration` step 6.a. */ function oneUnitFurther(date, unit, sign) { if (unit === "year") return { ...ZERO_DATE_DURATION, years: date.years + sign }; if (unit === "month") return adjustDateDuration(date, 0, 0, date.months + sign); return adjustDateDuration(date, 0, date.weeks + sign); } /** TC39 `BubbleRelativeDuration`. */ function bubbleRelativeDuration(sign, duration, nudgedEpochNs, context, largestUnit, smallestUnit) { let bubbled = duration; for (let index = UNITS.indexOf(smallestUnit) - 1; index >= UNITS.indexOf(largestUnit); index--) { const unit = UNITS[index]; if (unit === "week" && largestUnit !== "week") continue; const endDuration = oneUnitFurther(bubbled.date, unit, sign); if (bigintSign(nudgedEpochNs - windowBoundEpoch(context, endDuration)) === -sign) break; bubbled = { date: endDuration, time: 0n }; } return bubbled; } /** TC39 `RoundRelativeDuration` with a time zone. */ function roundRelativeDuration(duration, originEpochNs, destEpochNs, context, settings) { const { largestUnit, smallestUnit } = settings; const sign = internalDurationSign(duration) < 0 ? -1 : 1; const nudgeResult = nudgeRelativeDuration(sign, duration, originEpochNs, destEpochNs, context, settings); if (!nudgeResult.didExpandCalendarUnit || smallestUnit === "week") return nudgeResult.duration; return bubbleRelativeDuration(sign, nudgeResult.duration, nudgeResult.nudgedEpochNs, context, largestUnit, largerUnit(smallestUnit, "day")); } /** TC39 `DifferenceZonedDateTimeWithRounding`. */ function differenceZonedDateTimeWithRounding(ns1, ns2, context, settings) { const { largestUnit, smallestUnit, increment, roundingMode } = settings; if (!isDateUnit(largestUnit)) return { date: ZERO_DATE_DURATION, time: roundTimeDurationToIncrement(ns2 - ns1, BigInt(increment) * NANOSECONDS_PER_TIME_UNIT[smallestUnit], roundingMode) }; const difference = differenceZonedDateTime(ns1, ns2, context, largestUnit); if (smallestUnit === "nanosecond" && increment === 1) return difference; return roundRelativeDuration(difference, ns1, ns2, { ...context, wall: isoDateTimeFor(context.timeZone, ns1) }, settings); } /** An ISO date far from the limits, used only to validate options. */ const PLAIN_DATE_PROBE = new Temporal.PlainDate(2e3, 1, 1); /** TC39 `IsCalendarUnit`. */ function isCalendarUnit(unit) { return unit === "year" || unit === "month" || unit === "week"; } /** TC39 `RoundRelativeDuration` steps 1–5: the nudge for `settings.smallestUnit` in `context`. */ function nudgeRelativeDuration(sign, duration, originEpochNs, destEpochNs, context, settings) { const { largestUnit, smallestUnit, increment, roundingMode } = settings; const { timeZone } = context; if (isCalendarUnit(smallestUnit) || timeZone !== void 0 && smallestUnit === "day") return nudgeToCalendarUnit(sign, duration, originEpochNs, destEpochNs, context, increment, smallestUnit, roundingMode).nudgeResult; if (timeZone !== void 0) return nudgeToZonedTime(sign, duration, { ...context, timeZone }, increment, smallestUnit, roundingMode); return nudgeToDayOrTime(duration, destEpochNs, largestUnit, increment, smallestUnit, roundingMode); } /** TC39 `NudgeToDayOrTime`. */ function nudgeToDayOrTime(duration, destEpochNs, largestUnit, increment, smallestUnit, roundingMode) { const timeDuration = duration.time + BigInt(duration.date.days) * NANOSECONDS_PER_DAY; const roundedTime = roundTimeDurationToIncrement(timeDuration, (smallestUnit === "day" ? NANOSECONDS_PER_DAY : NANOSECONDS_PER_TIME_UNIT[smallestUnit]) * BigInt(increment), roundingMode); const wholeDays = timeDuration / NANOSECONDS_PER_DAY; const roundedWholeDays = roundedTime / NANOSECONDS_PER_DAY; const keepsDays = isDateUnit(largestUnit); return { duration: { date: adjustDateDuration(duration.date, keepsDays ? Number(roundedWholeDays) : 0), time: keepsDays ? roundedTime - roundedWholeDays * NANOSECONDS_PER_DAY : roundedTime }, nudgedEpochNs: destEpochNs + (roundedTime - timeDuration), didExpandCalendarUnit: bigintSign(roundedWholeDays - wholeDays) === bigintSign(timeDuration) }; } /** Nanoseconds since midnight on `wall`'s own date. */ function timeOfDayNanoseconds(wall) { return BigInt(wall.hour) * NANOSECONDS_PER_TIME_UNIT.hour + BigInt(wall.minute) * NANOSECONDS_PER_TIME_UNIT.minute + BigInt(wall.second) * NANOSECONDS_PER_TIME_UNIT.second + BigInt(wall.millisecond) * NANOSECONDS_PER_TIME_UNIT.millisecond + BigInt(wall.microsecond) * NANOSECONDS_PER_TIME_UNIT.microsecond + BigInt(wall.nanosecond); } /** TC39 `DifferenceISODateTime`, for two ISO-calendar wall clocks. */ function differenceISODateTime(one, two, calendar, largestUnit) { let time = timeOfDayNanoseconds(two) - timeOfDayNanoseconds(one); const timeSign = bigintSign(time); const dateSign = Temporal.PlainDate.compare(one.toPlainDate(), two.toPlainDate()); let adjustedDate = two.toPlainDate(); if (timeSign === dateSign) { adjustedDate = adjustedDate.add({ days: timeSign }); time -= BigInt(timeSign) * NANOSECONDS_PER_DAY; } const dateLargestUnit = largerUnit("day", largestUnit); const date = calendarDateUntil(calendar, one.toPlainDate(), adjustedDate, dateLargestUnit); if (largestUnit === dateLargestUnit) return { date, time }; return { date: adjustDateDuration(date, 0), time: time + BigInt(date.days) * NANOSECONDS_PER_DAY }; } function plainContext(calendar, wall) { return { timeZone: void 0, calendar, wall }; } /** TC39 `DifferencePlainDateTimeWithRounding`. */ function differencePlainDateTimeWithRounding(one, two, calendar, settings) { if (Temporal.PlainDateTime.compare(one, two) === 0) return { date: ZERO_DATE_DURATION, time: 0n }; const difference = differenceISODateTime(one, two, calendar, settings.largestUnit); if (settings.smallestUnit === "nanosecond" && settings.increment === 1) return difference; return roundRelativeDuration(difference, utcEpochNanoseconds(one), utcEpochNanoseconds(two), plainContext(calendar, one), settings); } /** TC39 `DifferencePlainDateTimeWithTotal`. */ function differencePlainDateTimeWithTotal(one, two, calendar, unit) { if (Temporal.PlainDateTime.compare(one, two) === 0) return 0; const difference = differenceISODateTime(one, two, calendar, unit); if (isCalendarUnit(unit)) return nudgeToCalendarUnit(internalDurationSign(difference) < 0 ? -1 : 1, difference, utcEpochNanoseconds(one), utcEpochNanoseconds(two), plainContext(calendar, one), 1, unit, "trunc").total; return divideToNumber(difference.time + BigInt(difference.date.days) * NANOSECONDS_PER_DAY, unit === "day" ? NANOSECONDS_PER_DAY : NANOSECONDS_PER_TIME_UNIT[unit]); } /** * The origin and target wall clocks TC39 `Duration#round` / `Duration#total` build from a plain * `relativeTo`: `ToInternalDurationRecordWith24HourDays`, `AddTime` from midnight, and * `CalendarDateAdd` of the date part plus the whole days that carried out of the time. */ function plainRelativeTarget(duration, plain) { const internal = toInternalDuration(duration); const time = internal.time + BigInt(internal.date.days) * NANOSECONDS_PER_DAY; let carriedDays = time / NANOSECONDS_PER_DAY; let timeOfDay = time % NANOSECONDS_PER_DAY; if (timeOfDay < 0n) { carriedDays -= 1n; timeOfDay += NANOSECONDS_PER_DAY; } const origin = plain.withCalendar("iso8601").toPlainDateTime(); return { origin, target: calendarDateAdd(plain.calendarId, origin.toPlainDate(), adjustDateDuration(internal.date, Number(carriedDays))).toPlainDateTime().add({ nanoseconds: Number(timeOfDay) }) }; } /** TC39 `DateDurationDays`. */ function dateDurationDays(date, plain) { const yearsMonthsWeeks = adjustDateDuration(date, 0); if (dateDurationSign(yearsMonthsWeeks) === 0) return date.days; const isoDate = plain.withCalendar("iso8601"); const later = calendarDateAdd(plain.calendarId, isoDate, yearsMonthsWeeks); return date.days + isoDate.until(later, { largestUnit: "day" }).days; } /** Runs `validate` (a polyfill call far from the limits); null when the options are invalid. */ function optionsAreValid(validate) { try { validate(); return true; } catch { return false; } } function contextOf(zoned) { return { timeZone: zoned.timeZoneId, calendar: zoned.calendarId }; } /** TC39 `DifferenceTemporalZonedDateTime(~until~, …)` for a date `largestUnit`. */ function untilAtLimit(one, two, options, settings) { if (!optionsAreValid(() => OPTIONS_PROBE.until(OPTIONS_PROBE, options)) || !isDateUnit(settings.largestUnit) || one.calendarId !== two.calendarId) return null; return temporalDurationFromInternal(differenceZonedDateTimeWithRounding(one.epochNanoseconds, two.epochNanoseconds, contextOf(one), settings), "hour"); } /** `Duration#total` with a zoned `relativeTo`: TC39 `DifferenceZonedDateTimeWithTotal`. */ function totalAtLimit(duration, zoned, unitOption, unit) { if (!optionsAreValid(() => ZERO_DURATION.total({ unit: unitOption, relativeTo: OPTIONS_PROBE }))) return null; const origin = zoned.epochNanoseconds; const target = addZonedDateTime(zoned, toInternalDuration(duration)); if (!isDateUnit(unit)) return divideToNumber(target - origin, NANOSECONDS_PER_TIME_UNIT[unit]); const context = contextOf(zoned); const difference = differenceZonedDateTime(origin, target, context, unit); return nudgeToCalendarUnit(internalDurationSign(difference) < 0 ? -1 : 1, difference, origin, target, { ...context, wall: isoDateTimeFor(context.timeZone, origin) }, 1, unit, "trunc").total; } /** `Duration#round` with a zoned `relativeTo`. */ function roundAtLimit(duration, zoned, roundTo, settings) { if (!canRoundBySpec(roundTo, settings, OPTIONS_PROBE)) return null; const { largestUnit } = settings; const target = addZonedDateTime(zoned, toInternalDuration(duration)); return temporalDurationFromInternal(differenceZonedDateTimeWithRounding(zoned.epochNanoseconds, target, contextOf(zoned), settings), isDateUnit(largestUnit) ? "hour" : largestUnit); } /** `Temporal.Duration.compare` with a zoned `relativeTo`, when either operand has date units. */ function compareAtLimit(one, two, zoned) { if (!isDateUnit(defaultLargestUnit(one)) && !isDateUnit(defaultLargestUnit(two))) return null; return bigintSign(addZonedDateTime(zoned, toInternalDuration(one)) - addZonedDateTime(zoned, toInternalDuration(two))); } /** Resolves the units of `until`/`round` options; null when a unit name is not one Temporal knows. */ function roundingSettings(largestUnitOption, smallestUnitOption, defaultLargestUnitFor, increment, roundingMode) { const smallestUnit = smallestUnitOption === void 0 ? "nanosecond" : toUnit(smallestUnitOption); if (smallestUnit === null) return null; const largestUnit = largestUnitOption === void 0 || largestUnitOption === "auto" ? defaultLargestUnitFor(smallestUnit) : toUnit(largestUnitOption); if (largestUnit === null) return null; return { largestUnit, smallestUnit, increment: increment ?? 1, roundingMode }; } /** True when `Duration#round` accepts `roundTo` with `settings`, checked far from any limit. */ function canRoundBySpec(roundTo, settings, probe) { const { largestUnit, smallestUnit, increment } = settings; return optionsAreValid(() => ZERO_DURATION.round({ ...roundTo, relativeTo: probe })) && largerUnit(largestUnit, smallestUnit) === largestUnit && !(increment > 1 && largestUnit !== smallestUnit && isDateUnit(smallestUnit)); } /** `Duration#total` with a plain `relativeTo`: TC39 `DifferencePlainDateTimeWithTotal`. */ function totalWithPlainRelativeTo(duration, plain, unitOption, unit) { if (!optionsAreValid(() => ZERO_DURATION.total({ unit: unitOption, relativeTo: PLAIN_DATE_PROBE }))) return null; const { origin, target } = plainRelativeTarget(duration, plain); return differencePlainDateTimeWithTotal(origin, target, plain.calendarId, unit); } /** `Duration#round` with a plain `relativeTo`: TC39 `DifferencePlainDateTimeWithRounding`. */ function roundWithPlainRelativeTo(duration, plain, roundTo, settings) { if (!canRoundBySpec(roundTo, settings, PLAIN_DATE_PROBE)) return null; const { origin, target } = plainRelativeTarget(duration, plain); return temporalDurationFromInternal(differencePlainDateTimeWithRounding(origin, target, plain.calendarId, settings), isDateUnit(settings.largestUnit) ? "hour" : settings.largestUnit); } export { NANOSECONDS_PER_DAY, NANOSECONDS_PER_TIME_UNIT, PLAIN_DATE_PROBE, atTimeOf, bigintAbs, bigintSign, calendarDateUntil, compareAtLimit, dateDurationDays, defaultLargestUnit, differencePlainDateTimeWithRounding, isCalendarUnit, isDateUnit, isoDateTimeFor, largerUnit, optionsAreValid, plainContext, roundAtLimit, roundRelativeDuration, roundWithPlainRelativeTo, roundingSettings, temporalDurationFromInternal, timeZoneAnnotation, toInternalDuration, toUnit, totalAtLimit, totalWithPlainRelativeTo, untilAtLimit };