@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.
44 lines (42 loc) • 2.32 kB
JavaScript
import { Temporal } from "./temporal.js";
import { isCalendarArithmeticCompatNeeded } from "./temporalCompat/capabilities.js";
import { calendarDateUntil } from "./temporalCompat/calendarDateArithmetic.js";
import { plainDateUntilWithRounding } from "./zonedDifference/calendarArithmetic.js";
// src/internal/plainDateUntil.ts
/** Plural date units to Temporal's singular spelling; anything else passes through unchanged. */
function singularDateUnit(unit) {
return unit.endsWith("s") ? unit.slice(0, -1) : unit;
}
/**
* `start.until(end, { largestUnit, ...rounding })` for two PlainDates in the same calendar.
*
* - Without rounding options the difference goes through the Temporal compat layer's
* `calendarDateUntil`, which is the polyfill's own `until` for `iso8601` and the TC39
* `NonISODateUntil` answer for other calendars (CORE-6 D1, D6, D7 and the corrected calendars).
* - With `smallestUnit`, `roundingIncrement` or `roundingMode`, a calendar whose compat is needed
* goes through `plainDateUntilWithRounding` (TC39 `DifferenceTemporalPlainDate` in the plain
* context, `GetUTCEpochNanoseconds`); every other calendar is the polyfill's own `until`.
*
* @param start PlainDate the difference starts from
* @param end PlainDate in the same calendar
* @param largestUnit a date unit, singular or plural
* @param options optional DifferenceOptions rounding controls
* @returns the difference as a Temporal.Duration; throws RangeError on invalid input
*
* @example plainDateUntil(Temporal.PlainDate.from("2024-01-31"), Temporal.PlainDate.from("2024-03-01"), "months").toString() // "P1M1D"
*/
function plainDateUntil(start, end, largestUnit, options) {
const smallestUnit = options?.smallestUnit;
const roundingIncrement = options?.roundingIncrement;
const roundingMode = options?.roundingMode;
if (smallestUnit === void 0 && roundingIncrement === void 0 && roundingMode === void 0) return Temporal.Duration.from(calendarDateUntil(start, end, singularDateUnit(largestUnit)));
const untilOptions = {
largestUnit,
smallestUnit,
roundingIncrement,
roundingMode
};
if (start.calendarId === end.calendarId && isCalendarArithmeticCompatNeeded(start.calendarId)) return plainDateUntilWithRounding(start, end, untilOptions);
return start.until(end, untilOptions);
}
export { plainDateUntil };