@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.
47 lines (45 loc) • 2.2 kB
JavaScript
import { fractionalDigitsOption } from "../../internal/typedOptions.js";
import { plainDateTimeOf } from "../../internal/inputChecks.js";
import { isOptionsArgument } from "../../internal/isObject.js";
import { defaultFractionalDigits } from "../../internal/defaultFractionalDigits.js";
import { isDateTimeUnitName } from "../../internal/unitNames.js";
import { resolveDateTimeUnit } from "../../internal/resolveDateTimeUnit.js";
import { resolveWeekStartsOn } from "../../internal/resolveWeekStartsOn.js";
import { startOfPlainDateTime } from "../../internal/plainDateSteps.js";
// src/plain/calculate/startOfDateTime.ts
/**
* Return the start of the specified date-time `unit` for a given ISO 8601 datetime string.
*
* - `unit` accepts the singular or plural name (`"month"` or `"months"`), as Temporal does.
* - Returns "" for invalid inputs.
*
* @param value ISO 8601 datetime string
* @param unit date or time unit, singular or plural, to specify the unit for the start
* @param optionsArg How the week is defined and how the result is written
* @returns ISO 8601 string representing the start of the specified unit, or "" on invalid input
*
* @example startOfDateTime("2024-02-29T12:34:56", "month") // "2024-02-01T00:00:00"
* @example startOfDateTime("2024-02-29T12:34:56.789", "milliseconds") // "2024-02-29T12:34:56.789"
* @example startOfDateTime("invalid-datetime", "month") // ""
*/
function startOfDateTime(value, unit, optionsArg) {
try {
if (!isOptionsArgument(optionsArg)) return "";
const weekStartsOn = resolveWeekStartsOn(optionsArg?.weekStartsOn);
const fractionalSecondDigits = fractionalDigitsOption(optionsArg?.fractionalSecondDigits);
const resolvedUnit = resolveDateTimeUnit(unit);
if (weekStartsOn === null || !isDateTimeUnitName(resolvedUnit)) return "";
const source = plainDateTimeOf(value);
if (source === null) return "";
try {
const result = startOfPlainDateTime(source, resolvedUnit, weekStartsOn);
const fractionalDigits = defaultFractionalDigits(resolvedUnit, fractionalSecondDigits);
return result.toString({ fractionalSecondDigits: fractionalDigits });
} catch {
return "";
}
} catch {
return "";
}
}
export { startOfDateTime };