@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.
40 lines (38 loc) • 1.95 kB
JavaScript
import { zonedDateTimeOf, zonedDateTimesOf } from "../../internal/zonedWallClock.js";
// src/zoned/calculate/closestZonedTo.ts
/**
* Return the candidate zoned datetime nearest to `target` by temporal distance.
*
* - Distance is measured in total days using `Temporal.Instant` epoch milliseconds.
* - Returns `""` if the candidates array is empty or contains no valid dates, or `target` is invalid.
* - **Compatibility:** before 1.16.0 invalid input returned `null`.
* - On a tie (two equidistant candidates), returns the first one in array order.
*
* @param target ISO ZonedDateTime string to measure distance from
* @param candidates Array of ISO ZonedDateTime strings to choose from
* @returns The nearest candidate zoned datetime string, or "" on invalid input
*
* @example closestZonedTo("2024-03-15T12:00:00+00:00[UTC]", ["2024-03-01T00:00:00+00:00[UTC]", "2024-03-20T00:00:00+00:00[UTC]", "2024-03-18T00:00:00+00:00[UTC]"]) // "2024-03-18T00:00:00+00:00[UTC]"
* @example closestZonedTo("2024-03-15T12:00:00+00:00[UTC]", ["2024-03-01T00:00:00+00:00[UTC]", "2024-03-29T00:00:00+00:00[UTC]"]) // "2024-03-29T00:00:00+00:00[UTC]"
* @example closestZonedTo("2024-03-15T12:00:00+00:00[UTC]", []) // ""
* @example closestZonedTo("invalid", ["2024-03-01T00:00:00+00:00[UTC]"]) // ""
*/
function closestZonedTo(target, candidates) {
try {
const t = zonedDateTimeOf(target);
if (t === null || !Array.isArray(candidates) || !candidates.length) return "";
try {
const parsed = zonedDateTimesOf(candidates);
if (!parsed.length) return "";
return parsed.reduce((best, candidate) => {
const bestDist = Math.abs(best.toInstant().epochMilliseconds - t.toInstant().epochMilliseconds) / 864e5;
return Math.abs(candidate.toInstant().epochMilliseconds - t.toInstant().epochMilliseconds) / 864e5 < bestDist ? candidate : best;
}, parsed[0]).toString();
} catch {
return "";
}
} catch {
return "";
}
}
export { closestZonedTo };