@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.
49 lines (47 loc) • 1.79 kB
JavaScript
import { plainDateOf } from "../../internal/inputChecks.js";
import { isOptionsArgument } from "../../internal/isObject.js";
import { resolveDateTimeUnit } from "../../internal/resolveDateTimeUnit.js";
import { resolveWeekStartsOn } from "../../internal/resolveWeekStartsOn.js";
import { startOfPlainDate } from "../../internal/plainDateSteps.js";
// src/plain/calculate/startOfDate.ts
const supported = [
"year",
"month",
"week",
"day"
];
/**
* Return the start of the specified date `unit` for a given ISO 8601 date string.
*
* - `"day"` returns the date itself: a date is already a whole day, as `endOfDate` treats it.
* - `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 start
* @param optionsArg How the week is defined
* @returns ISO 8601 string representing the start of the specified unit, or "" on invalid input
*
* @example startOfDate("2024-02-29", "month") // "2024-02-01"
* @example startOfDate("2024-02-29", "day") // "2024-02-29"
* @example startOfDate("2024-02-29", "months") // "2024-02-01"
* @example startOfDate("invalid-date", "month") // ""
*/
function startOfDate(value, unit, optionsArg) {
try {
if (!isOptionsArgument(optionsArg)) return "";
const resolvedUnit = resolveDateTimeUnit(unit);
const weekStartsOn = resolveWeekStartsOn(optionsArg?.weekStartsOn);
if (weekStartsOn === null || !supported.includes(resolvedUnit)) return "";
const source = plainDateOf(value);
if (source === null) return "";
try {
return startOfPlainDate(source, resolvedUnit, weekStartsOn).toString();
} catch {
return "";
}
} catch {
return "";
}
}
export { startOfDate };