UNPKG

@burglekitt/gmt

Version:

Temporal-based date and time utilities with timezone support and polyfill integration

51 lines (50 loc) 1.89 kB
import { Temporal } from "@js-temporal/polyfill"; import { isValidDate } from "../validate/index.js"; const supported = ["year", "month", "week"]; /** * Return the start of the specified date `unit` for a given ISO 8601 date string. * * - Returns "" for invalid inputs. * * @param value ISO 8601 date string * @param unit Temporal.DateUnit to specify the unit for the start * @param optionsArg optional: weekStartsOn ("monday" | "sunday") * @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("invalid-date", "month") // "" */ export function startOfDate(value, unit, optionsArg) { const weekStartsOn = optionsArg?.weekStartsOn ?? "monday"; if (!isValidDate(value) || !supported.includes(unit)) return ""; try { const source = Temporal.PlainDate.from(value); let result; switch (unit) { case "year": result = source.with({ month: 1, day: 1 }); break; case "month": result = source.with({ day: 1 }); break; case "week": { // Week start: compute how many days to subtract to reach Monday. // Temporal: 1 (Mon) to 7 (Sun) // If Monday start: Monday(1) subtracts 0, Sunday(7) subtracts 6. // If Sunday start: Sunday(7) subtracts 0, Monday(1) subtracts 1. const daysToSubtract = weekStartsOn === "monday" ? source.dayOfWeek - 1 : source.dayOfWeek % 7; result = source.subtract({ days: daysToSubtract }); break; } default: return ""; } return result.toString(); } catch { return ""; } }