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.

121 lines (119 loc) • 6.67 kB
import { Temporal } from "../../internal/temporal.js"; import { isObject } from "../../internal/isObject.js"; import { defaultFractionalDigits } from "../../internal/defaultFractionalDigits.js"; import { isValidDateTimeUnit } from "../validate/isValidDateTimeUnit.js"; import { resolveDateTimeUnit } from "../../internal/resolveDateTimeUnit.js"; import { isValidDateTime } from "../validate/isValidDateTime.js"; import { getDaysIntoDateUnit } from "../../internal/dateUnitHelpers.js"; import { measureNearRangeEnd } from "../../internal/measureNearRangeEnd.js"; import { resolveManualRoundingOptions } from "../../internal/resolveManualRoundingOptions.js"; import { addDateTimeUnit, getStartOfDateTimeUnit, getStartOfNextDateTimeUnit } from "../../internal/dateTimeUnitHelpers.js"; // src/plain/calculate/roundDateTime.ts const MILLISECONDS_PER_DAY = 864e5; /** Milliseconds (with sub-millisecond fraction) from midnight to `source`'s wall-clock time. */ function millisecondsIntoDay(source) { return source.hour * 36e5 + source.minute * 6e4 + source.second * 1e3 + source.millisecond + source.microsecond / 1e3 + source.nanosecond / 1e6; } /** Temporal.PlainDateTime.round() in this polyfill supports day and time units. */ const TIME_UNITS = [ "day", "hour", "minute", "second", "millisecond", "microsecond", "nanosecond" ]; /** Round a day or time unit through Temporal.PlainDateTime.round(). Throws on invalid options. */ function roundTimeUnit(source, smallestUnit, roundingIncrement, roundingMode) { const result = source.round({ smallestUnit, roundingIncrement, roundingMode }); const fractionalDigits = defaultFractionalDigits(smallestUnit); return result.toString({ fractionalSecondDigits: fractionalDigits }); } /** Rounds up at or past the half-way point. */ const upAtHalf = (_elapsedMs, fraction) => fraction() >= .5; /** Rounds up only past the half-way point. */ const upPastHalf = (_elapsedMs, fraction) => fraction() > .5; /** * Whether a date unit rounds up to the next start, per rounding mode. * * `fraction` is the position within the unit, computed lazily because only the half modes need it. */ const ROUNDS_UP_TO_NEXT_START = { ceil: (elapsedMs) => elapsedMs > 0, expand: (elapsedMs) => elapsedMs > 0, floor: () => false, trunc: () => false, halfExpand: upAtHalf, halfCeil: upAtHalf, halfTrunc: upPastHalf, halfFloor: upPastHalf, halfEven: upPastHalf }; /** Manually round to a date unit (year, month, week). Throws when a needed start is out of range. */ function roundDateUnit(source, smallestUnit, increment, mode) { const elapsedMs = getDaysIntoDateUnit(source, smallestUnit) * MILLISECONDS_PER_DAY + millisecondsIntoDay(source); const startOfNextFrom = (from) => addDateTimeUnit(getStartOfNextDateTimeUnit(from, smallestUnit), smallestUnit, increment - 1); const fraction = () => elapsedMs / (elapsedMs + measureNearRangeEnd(source, (from) => from.until(startOfNextFrom(from)).total("milliseconds"))); return (ROUNDS_UP_TO_NEXT_START[mode](elapsedMs, fraction) ? startOfNextFrom(source) : getStartOfDateTimeUnit(source, smallestUnit)).toString(); } /** * Round an ISO 8601 datetime string to the specified date-time unit. * * - Returns "" for invalid inputs. * - Time units use Temporal.PlainDateTime.round() directly. * - Date units (year, month, week) use manual start-of-unit rounding. Weeks start on Monday. * - For date units the rounding grid is anchored at the unit containing `value`, so `"halfEven"` * breaks an exact tie towards that unit's start (multiple 0, the even one). Time units round * through Temporal, which anchors half-even on its own absolute grid. * - For date units the position within the unit is measured towards the next start, so a value in * a unit that began before the first representable PlainDateTime * (`-271821-04-19T00:00:00.000000001`) still rounds up to the next start. When it rounds down to * that unrepresentable start, the result is "". * - In the last representable year (`+275760`) a value that rounds down to a date unit still * returns that unit's start; only rounding up past `+275760-09-13T23:59:59.999999999` returns "". * - Wraps all Temporal calls in try-catch; returns "" on any error. * - Output precision follows `smallestUnit`: no fractional seconds for "second" and coarser, * 3 digits for "millisecond", 6 for "microsecond" and 9 for "nanosecond", so the result never * hides the precision the unit asked for. * * @param value ISO 8601 datetime string * @param options The unit to round to and how to round * @returns Rounded ISO 8601 datetime string, or "" on invalid input * * @example roundDateTime("2024-06-15T12:34:56", { smallestUnit: "year" }) // "2024-01-01T00:00:00" * @example roundDateTime("2024-06-15T12:34:56", { smallestUnit: "month" }) // "2024-06-01T00:00:00" (under half way: rounds down) * @example roundDateTime("2024-06-16T12:34:56", { smallestUnit: "month" }) // "2024-07-01T00:00:00" (past half way: rounds up) * @example roundDateTime("-271821-04-19T12:00:00", { smallestUnit: "month" }) // "-271821-05-01T00:00:00" (the month began before the range) * @example roundDateTime("+275760-06-15T00:00:00", { smallestUnit: "year", roundingMode: "floor" }) // "+275760-01-01T00:00:00" (the next year is past the range) * @example roundDateTime("2024-06-15T12:34:56", { smallestUnit: "day" }) // "2024-06-16T00:00:00" * @example roundDateTime("2024-06-15T12:34:56", { smallestUnit: "hour" }) // "2024-06-15T13:00:00" * @example roundDateTime("2024-06-15T12:34:56", { smallestUnit: "hours" }) // "2024-06-15T13:00:00" (plural unit name) * @example roundDateTime("2024-06-15T12:34:56.123456789", { smallestUnit: "millisecond" }) // "2024-06-15T12:34:56.123" (precision follows the unit) * @example roundDateTime("2024-05-15T12:00:00", { smallestUnit: "month", roundingMode: "bogus" as never }) // "" * @example roundDateTime("invalid", { smallestUnit: "year" }) // "" */ function roundDateTime(value, options) { try { if (!isObject(options)) return ""; const { roundingIncrement, roundingMode } = options; const smallestUnit = resolveDateTimeUnit(options.smallestUnit); if (!isValidDateTime(value) || !isValidDateTimeUnit(smallestUnit)) return ""; try { const source = Temporal.PlainDateTime.from(value); if (TIME_UNITS.includes(smallestUnit)) return roundTimeUnit(source, smallestUnit, roundingIncrement, roundingMode); const resolved = resolveManualRoundingOptions(roundingIncrement, roundingMode); if (resolved === null) return ""; return roundDateUnit(source, smallestUnit, resolved.increment, resolved.mode); } catch { return ""; } } catch { return ""; } } export { roundDateTime };