@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.41 kB
JavaScript
import { Temporal } from "../../internal/temporal.js";
import { isValidDate } from "../validate/isValidDate.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);
if (weekStartsOn === null || !isValidDate(value) || !supported.includes(resolvedUnit)) return "";
try {
const source = Temporal.PlainDate.from(value);
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 };