@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.
34 lines (32 loc) • 1.29 kB
JavaScript
import { Temporal } from "../../internal/temporal.js";
import { zonedDateTimesOf } from "../../internal/zonedWallClock.js";
// src/zoned/calculate/maxZoned.ts
/**
* Return the latest (maximum) of the given ZonedDateTime values.
*
* - Returns null if the array is empty or contains no valid dates.
* - Validation is performed on each item in the array.
*
* @param zonedDateTimes Array of ISO ZonedDateTime strings
* @returns The latest zoned datetime string, or null on invalid input
*
* @example maxZoned(["2024-03-10T12:00:00[Asia/Kolkata]", "2024-03-15T12:00:00[Asia/Kolkata]"]) // "2024-03-15T12:00:00+05:30[Asia/Kolkata]"
* @example maxZoned(["invalid", "2024-03-15T12:00:00[Asia/Kolkata]"]) // "2024-03-15T12:00:00+05:30[Asia/Kolkata]"
* @example maxZoned(["invalid", "also invalid"]) // null
* @example maxZoned([]) // null
*/
function maxZoned(zonedDateTimes) {
try {
if (!Array.isArray(zonedDateTimes) || !zonedDateTimes.length) return null;
const valid = zonedDateTimesOf(zonedDateTimes);
if (!valid.length) return null;
try {
return valid.reduce((currentMax, candidate) => Temporal.ZonedDateTime.compare(candidate, currentMax) > 0 ? candidate : currentMax, valid[0]).toString();
} catch {
return null;
}
} catch {
return null;
}
}
export { maxZoned };