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.

37 lines (35 loc) • 1.3 kB
import { Temporal } from "../../internal/temporal.js"; import { isValidUtc } from "../validate/isValidUtc.js"; // src/utc/calculate/maxUtc.ts /** * Return the latest (maximum) of the given UTC datetime values. * * - Filters invalid values before finding maximum. * - Returns null if array is empty or has no valid values. * * @param utcDateTimes Array of ISO datetime strings (e.g. "2024-03-10T12:00:00Z") * @returns The latest UTC datetime string, or null on invalid input * * @example maxUtc(["2024-03-10T12:00:00Z", "2024-03-15T12:00:00Z", "2024-03-12T12:00:00Z"]) // "2024-03-15T12:00:00Z" * @example maxUtc(["invalid", "2024-03-15T12:00:00Z"]) // "2024-03-15T12:00:00Z" * @example maxUtc(["invalid", "also invalid"]) // null * @example maxUtc([]) // null */ function maxUtc(utcDateTimes) { try { if (!Array.isArray(utcDateTimes) || !utcDateTimes.length) return null; const valid = utcDateTimes.filter(isValidUtc); if (!valid.length) return null; try { return valid.reduce((currentMax, candidateStr) => { const candidate = Temporal.Instant.from(candidateStr); return Temporal.Instant.compare(candidate, currentMax) > 0 ? candidate : currentMax; }, Temporal.Instant.from(valid[0])).toString(); } catch { return null; } } catch { return null; } } export { maxUtc };