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.

102 lines (100 loc) • 2.97 kB
import { Temporal } from "../../internal/temporal.js"; import { isOptionsArgument } from "../../internal/isObject.js"; import { resolveDateTimeUnit } from "../../internal/resolveDateTimeUnit.js"; import { isValidTime } from "../validate/isValidTime.js"; // src/plain/calculate/endOfTime.ts const supported = [ "day", "hour", "minute", "second", "millisecond", "microsecond", "nanosecond" ]; /** * Return the end of the specified time `unit` for a given ISO 8601 time string. * * - `unit` accepts the singular or plural name (`"hour"` or `"hours"`), as Temporal does. * - Returns "" for invalid inputs. * - **Compatibility:** before 1.16.0 the default printed only the digits the unit names — none for * `second` and coarser, 3 for `millisecond`, 6 for `microsecond` — which wrote a moment earlier * than the end. Pass that `fractionalSecondDigits` to keep the previous string. * * @param value ISO 8601 time string * @param unit EndOfTimeUnit to specify the unit for the end * @param optionsArg How the result is written * @returns ISO 8601 string representing the end of the specified unit, or "" on invalid input * * @example endOfTime("12:34:56", "hour") // "12:59:59.999999999" * @example endOfTime("12:34:56", "hour", { fractionalSecondDigits: 0 }) // "12:59:59" — the pre-1.16.0 string * @example endOfTime("12:34:56.123", "milliseconds") // "12:34:56.123999999" * @example endOfTime("invalid", "hour") // "" */ function endOfTime(value, unit, optionsArg) { try { if (!isOptionsArgument(optionsArg)) return ""; const fractionalSecondDigits = optionsArg?.fractionalSecondDigits; const resolvedUnit = resolveDateTimeUnit(unit); if (!isValidTime(value) || !supported.includes(resolvedUnit)) return ""; try { const source = Temporal.PlainTime.from(value); let result; switch (resolvedUnit) { case "day": result = source.with({ hour: 23, minute: 59, second: 59, millisecond: 999, microsecond: 999, nanosecond: 999 }); break; case "hour": result = source.with({ minute: 59, second: 59, millisecond: 999, microsecond: 999, nanosecond: 999 }); break; case "minute": result = source.with({ second: 59, millisecond: 999, microsecond: 999, nanosecond: 999 }); break; case "second": result = source.with({ millisecond: 999, microsecond: 999, nanosecond: 999 }); break; case "millisecond": result = source.with({ microsecond: 999, nanosecond: 999 }); break; case "microsecond": result = source.with({ nanosecond: 999 }); break; case "nanosecond": result = source; break; default: return ""; } return result.toString({ fractionalSecondDigits: fractionalSecondDigits === void 0 ? 9 : fractionalSecondDigits }); } catch { return ""; } } catch { return ""; } } export { endOfTime };