@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) • 1.89 kB
JavaScript
import { isOptionsArgument } from "../../internal/isObject.js";
import { resolveWeekStartsOn } from "../../internal/resolveWeekStartsOn.js";
import { weekNumberOf } from "../../internal/weekNumber.js";
import { unixWallClock } from "../../internal/unixWallClock.js";
// src/unix/parse/parseWeekFromUnix.ts
/**
* Return the week number from a unix epoch value.
*
* - Returns the week of the week-year, 1–53, so late-December days can be week 1 of the next
* year — see `getWeekNumber`.
* - Returns null for invalid input.
*
* @param value unix epoch in milliseconds or seconds: a safe integer, or a string of optionally negative ASCII digits
* @param options optional: how `value` is read, the zone its date is read in and the first day of the week; a non-object value (such as `null`) is invalid
* @returns Week number (1-53 for "monday" and for "sunday") or null on invalid input
*
* @example parseWeekFromUnix(1704067200000, { timeZone: "UTC" }) // 1
* @example parseWeekFromUnix(1704067200000, { weekStartsOn: "sunday", timeZone: "UTC" }) // 1
* @example parseWeekFromUnix(-86400, { epochUnit: "seconds" }) // 1
* @example parseWeekFromUnix("1704067200000") // 1 (digit string, UTC by default)
* @example parseWeekFromUnix("") // null (a blank string is not epoch 0)
* @example parseWeekFromUnix(1735646400000, { weekStartsOn: "sunday", timeZone: "UTC" }) // 1 (2024-12-31T12:00:00Z; its Sunday-first week holds 1 January 2025)
*/
function parseWeekFromUnix(value, options) {
try {
if (!isOptionsArgument(options)) return null;
const wallClock = unixWallClock(value, options);
const weekStartsOn = resolveWeekStartsOn(options?.weekStartsOn);
if (wallClock === null || weekStartsOn === null) return null;
try {
return weekNumberOf(wallClock.toPlainDate(), weekStartsOn);
} catch {
return null;
}
} catch {
return null;
}
}
export { parseWeekFromUnix };