@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.18 kB
JavaScript
import { Temporal } from "../../internal/temporal.js";
import { isOptionsArgument } from "../../internal/isObject.js";
import { frameWallClock, normalizeZoneFrame } from "../../internal/zoneFrame.js";
import { resolveWeekStartsOn } from "../../internal/resolveWeekStartsOn.js";
import { getWeekNumber } from "../../plain/calculate/getWeekNumber.js";
import { isValidUtc } from "../validate/isValidUtc.js";
// src/utc/parse/parseWeekFromUtc.ts
/**
* Return the week number from a UTC datetime string.
*
* - The result is the week of the week-year, 1–53, so late-December days can be week 1 of the next
* year: 2024-12-31 → 1 under either numbering, and 2000-12-30 → 53 under the Sunday-first one
* (minimal days 1).
* - Returns null for invalid input.
*
* @param value ISO UTC datetime string (e.g., "2024-03-17T14:30:45Z")
* @param optionsArg How weeks are numbered, and the time zone the value is read in
* @returns Week number (1-53), or null on invalid input
*
* @example parseWeekFromUtc("2024-03-17T14:30:45Z") // 11
* @example parseWeekFromUtc("2024-12-31T12:00:00Z") // 1 (ISO week 1 of 2025)
* @example parseWeekFromUtc("2024-12-31T12:00:00Z", { weekStartsOn: "sunday" }) // 1 (its Sunday-first week holds 1 January 2025)
* @example parseWeekFromUtc("2000-12-31T12:00:00Z", { weekStartsOn: "sunday" }) // 1 (its Sunday-first week holds 1 January 2001)
* @example parseWeekFromUtc("2024-03-17T02:30:45Z", { weekStartsOn: "sunday", timeZone: "America/Sao_Paulo" }) // 11 (Saturday 16 March in São Paulo)
* @example parseWeekFromUtc("invalid") // null
*/
function parseWeekFromUtc(value, optionsArg) {
try {
if (!isOptionsArgument(optionsArg)) return null;
if (!isValidUtc(value)) return null;
const weekStartsOn = resolveWeekStartsOn(optionsArg?.weekStartsOn);
const frame = normalizeZoneFrame(optionsArg?.timeZone);
if (weekStartsOn === null || frame === null) return null;
try {
const instant = Temporal.Instant.from(value);
const dateStr = frameWallClock(instant, frame).toPlainDate().toString();
return getWeekNumber(dateStr, weekStartsOn);
} catch {
return null;
}
} catch {
return null;
}
}
export { parseWeekFromUtc };