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.

51 lines (49 loc) • 2.15 kB
import { Temporal } from "../../internal/temporal.js"; import { isObject } from "../../internal/isObject.js"; import { defaultFractionalDigits } from "../../internal/defaultFractionalDigits.js"; import { resolveDateTimeUnit } from "../../internal/resolveDateTimeUnit.js"; import { isValidTime } from "../validate/isValidTime.js"; import { isValidTimeUnit } from "../validate/isValidTimeUnit.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 (!isObject(options)) return ""; const { roundingIncrement, roundingMode } = options; const smallestUnit = resolveDateTimeUnit(options.smallestUnit); if (!isValidTime(value) || !isValidTimeUnit(smallestUnit)) return ""; try { const result = Temporal.PlainTime.from(value).round({ smallestUnit, roundingIncrement, roundingMode }); const fractionalDigits = defaultFractionalDigits(smallestUnit); return result.toString({ fractionalSecondDigits: fractionalDigits }); } catch { return ""; } } catch { return ""; } } export { roundTime };