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.

70 lines (68 loc) • 2.34 kB
import { plainDateOf } from "../../internal/inputChecks.js"; import { isOptionsArgument } from "../../internal/isObject.js"; import { resolveDateTimeUnit } from "../../internal/resolveDateTimeUnit.js"; import { resolveWeekStartsOn } from "../../internal/resolveWeekStartsOn.js"; // src/plain/calculate/endOfDate.ts const supported = [ "year", "month", "week", "day" ]; /** * Return the end of the specified date `unit` for a given ISO 8601 date string. * * - The end is computed forward from `value`, so it is returned even when the unit began before * the first representable date (`-271821-04-19`). * - `unit` accepts the singular or plural name (`"month"` or `"months"`), as Temporal does. * - Returns "" for invalid inputs. * * @param value ISO 8601 date string * @param unit date unit, singular or plural, to specify the unit for the end * @param optionsArg How the week is defined * @returns ISO 8601 string representing the end of the specified unit, or "" on invalid input * * @example endOfDate("2024-02-29", "month") // "2024-02-29" * @example endOfDate("2024-03-03", "week", { weekStartsOn: "sunday" }) // "2024-03-09" * @example endOfDate("-271821-04-19", "month") // "-271821-04-30" (the month began before the range; its end did not) * @example endOfDate("2024-02-29", "years") // "2024-12-31" * @example endOfDate("invalid-date", "month") // "" */ function endOfDate(value, unit, optionsArg) { try { if (!isOptionsArgument(optionsArg)) return ""; const resolvedUnit = resolveDateTimeUnit(unit); const weekStartsOn = resolveWeekStartsOn(optionsArg?.weekStartsOn); const source = plainDateOf(value); if (weekStartsOn === null || source === null || !supported.includes(resolvedUnit)) return ""; try { let result; switch (resolvedUnit) { case "year": result = source.with({ month: 12, day: 31 }); break; case "month": result = source.with({ day: source.daysInMonth }); break; case "week": { const daysToEndOfWeek = weekStartsOn === "monday" ? 7 - source.dayOfWeek : 6 - source.dayOfWeek % 7; result = source.add({ days: daysToEndOfWeek }); break; } case "day": result = source; break; default: return ""; } return result.toString(); } catch { return ""; } } catch { return ""; } } export { endOfDate };