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.

71 lines (69 loc) • 2.76 kB
import { plainTimeOf } from "../../internal/inputChecks.js"; import { nowPlainTimeISO } from "../../internal/temporalCompat/clock.js"; import { isOptionsObject } from "../../internal/isObject.js"; import { resolveRelativeUnit } from "../../internal/resolveRelativeUnit.js"; import { formatRelativeAmount } from "../../internal/formatRelativeDuration.js"; // src/plain/format/formatRelativeTime.ts const TIME_UNITS = [ "hour", "minute", "second" ]; const AUTO_UNITS = [ { unit: "second", maxSeconds: 60 }, { unit: "minute", maxSeconds: 3600 }, { unit: "hour", maxSeconds: Infinity } ]; /** * Format the relative time between a plain time and a reference time. * * - Auto-picks the display unit (second/minute/hour) based on the distance, unless * `largestUnit` forces one. * - `largestUnit` is one of those three units, singular or plural. Any other value returns `""`. * - `options` must be an object or omitted: `null` or any other primitive returns `""`, as * Temporal's GetOptionsObject rejects it. * * @param value ISO time string to format * @param locale optional: BCP 47 locale tag, or a preference list of tags (ECMA-402) * @param options How the distance is measured, rounded and worded * @returns the formatted relative-time string, or "" on invalid input * * @example formatRelativeTime("14:30:00", "de-DE", { style: "short", reference: "16:30:00" }) // "vor 2 Std." * @example formatRelativeTime("09:00:00", "en-GB", { reference: "10:30:00", roundingMethod: "floor" }) // "2 hours ago" (−1.5 hours floors to −2) * @example formatRelativeTime("not-a-time") // "" * @example formatRelativeTime("10:00:00", ["fr-FR", "en-US"], { reference: "12:00:00" }) // "il y a 2 heures" * @example formatRelativeTime("10:00:00", "ja-JP", null as never) // "" (null options) */ function formatRelativeTime(value, locale, options = {}) { try { if (!isOptionsObject(options)) return ""; const target = plainTimeOf(value); if (target === null) return ""; const referenceOption = options.reference; const referenceOptionParsed = plainTimeOf(referenceOption); if (referenceOption !== void 0 && referenceOptionParsed === null) return ""; try { const forcedUnit = resolveRelativeUnit(options.largestUnit, TIME_UNITS); const roundingMethod = options.roundingMethod; const reference = referenceOptionParsed ?? nowPlainTimeISO(); const diff = target.since(reference); const absSeconds = Math.abs(diff.total("second")); const unit = forcedUnit === void 0 ? AUTO_UNITS.find((t) => absSeconds < t.maxSeconds)?.unit ?? "hour" : forcedUnit; return formatRelativeAmount(diff.total(unit), unit, locale, options, roundingMethod); } catch { return ""; } } catch { return ""; } } export { formatRelativeTime };