@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.
69 lines (67 loc) • 2.21 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/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 || !isValidDate(value) || !supported.includes(resolvedUnit)) return "";
try {
const source = Temporal.PlainDate.from(value);
let result;
switch (resolvedUnit) {
case "year":
result = source.with({
month: 1,
day: 1
});
break;
case "month":
result = source.with({ day: 1 });
break;
case "day":
result = source;
break;
case "week": {
const daysToSubtract = weekStartsOn === "monday" ? source.dayOfWeek - 1 : source.dayOfWeek % 7;
result = source.subtract({ days: daysToSubtract });
break;
}
default: return "";
}
return result.toString();
} catch {
return "";
}
} catch {
return "";
}
}
export { startOfDate };