@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.
41 lines (39 loc) • 2.17 kB
JavaScript
import { isOptionsArgument } from "../../internal/isObject.js";
import { optionOrDefault } from "../../internal/optionOrDefault.js";
import { zonedDateTimeFrom } from "../../internal/zonedWallClock.js";
import { isValidZonedDateTime } from "../validate/isValidZonedDateTime.js";
import { zonedUnitStart } from "../../internal/zonedBucket.js";
// src/zoned/calculate/startOfQuarterForZoned.ts
/**
* Return the start of the quarter for a given zoned ISO datetime.
*
* - Calculates which quarter (1-4) the date falls into and returns the first instant of that quarter, with every field below the day reset — milliseconds, microseconds and nanoseconds included.
* - Returns the real start of the local quarter in `value`'s own zone (see `floorToZone`), so the result is never after `value`: a skipped first midnight starts at the quarter's first real instant, and a repeated one (`Africa/Tunis`, 1978-10-01) at its first pass.
* - Validation is performed on the input.
*
* @param value ISO ZonedDateTime string
* @param optionsArg optional setting for the precision of the output string
* @returns ISO ZonedDateTime string for the start of the quarter, or "" on invalid input
*
* @example startOfQuarterForZoned("2024-02-15T14:30:00+00:00[UTC]") // "2024-01-01T00:00:00+00:00[UTC]"
* @example startOfQuarterForZoned("2024-05-10T10:00:00+00:00[UTC]") // "2024-04-01T00:00:00+00:00[UTC]"
* @example startOfQuarterForZoned("2024-11-20T08:00:00+00:00[UTC]") // "2024-10-01T00:00:00+00:00[UTC]"
* @example startOfQuarterForZoned("2024-02-15T14:30:00+00:00[UTC]", { fractionalSecondDigits: 3 }) // "2024-01-01T00:00:00.000+00:00[UTC]"
* @example startOfQuarterForZoned("invalid") // ""
*/
function startOfQuarterForZoned(value, optionsArg) {
try {
if (!isOptionsArgument(optionsArg)) return "";
if (!isValidZonedDateTime(value)) return "";
const fractionalSecondDigits = optionOrDefault(optionsArg?.fractionalSecondDigits, 0);
try {
const start = zonedUnitStart(zonedDateTimeFrom(value), "quarter");
return start ? start.toString({ fractionalSecondDigits }) : "";
} catch {
return "";
}
} catch {
return "";
}
}
export { startOfQuarterForZoned };