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.

52 lines (50 loc) • 2.2 kB
import { roundingMembers } from "../../internal/typedOptions.js"; import { plainTimeOf } from "../../internal/inputChecks.js"; import { isOptionsObject } from "../../internal/isObject.js"; import { defaultFractionalDigits } from "../../internal/defaultFractionalDigits.js"; import { isTimeUnitName } from "../../internal/unitNames.js"; import { resolveDateTimeUnit } from "../../internal/resolveDateTimeUnit.js"; // src/plain/calculate/roundTime.ts /** * Round an ISO 8601 time string to the specified time unit. * * - Returns "" for invalid inputs. * - Wraps Temporal.PlainTime.round() which throws on invalid options. * - 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 time string * @param options The unit to round to and how to round * @returns Rounded ISO 8601 time string, or "" on invalid input * * @example roundTime("12:34:56", { smallestUnit: "hour" }) // "13:00:00" * @example roundTime("12:34:56", { smallestUnit: "minute" }) // "12:35:00" * @example roundTime("12:34:56", { smallestUnit: "second", roundingMode: "floor" }) // "12:34:56" * @example roundTime("12:34:56", { smallestUnit: "hours" }) // "13:00:00" (plural unit name) * @example roundTime("12:34:56.123456789", { smallestUnit: "microsecond" }) // "12:34:56.123457" (precision follows the unit) * @example roundTime("invalid", { smallestUnit: "hour" }) // "" */ function roundTime(value, options) { try { if (!isOptionsObject(options)) return ""; const { roundingIncrement, roundingMode } = roundingMembers(options); const smallestUnit = resolveDateTimeUnit(options.smallestUnit); const source = plainTimeOf(value); if (source === null || !isTimeUnitName(smallestUnit)) return ""; try { const result = source.round({ smallestUnit, roundingIncrement, roundingMode }); const fractionalDigits = defaultFractionalDigits(smallestUnit); return result.toString({ fractionalSecondDigits: fractionalDigits }); } catch { return ""; } } catch { return ""; } } export { roundTime };