@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.
46 lines (44 loc) • 2.25 kB
JavaScript
import { Temporal } from "../../internal/temporal.js";
import { isValidDate } from "../validate/isValidDate.js";
import { getLocaleFirstDayOfWeek } from "../../internal/getLocaleFirstDayOfWeek.js";
import { monthGridWeekRow } from "../../internal/monthGridWeekRow.js";
// src/plain/calculate/getWeekOfMonth.ts
/**
* Return the 1-based row `value` falls on within its month's calendar
* grid, using `locale`'s first day of week.
*
* - Week 1 is the row containing the 1st of the month: UTS #35's week of month (`W`, Part 4 Dates
* § Week Data) with the locale's first day of week and minimal days fixed at 1. The locale's own
* minDays (4 in much of Europe) is not applied, so a short leading week still counts: a month
* grid draws every day of the month.
* - Distinct from ISO `weekOfYear`: this counts rows within a single
* month's grid, reset every month, rather than weeks since Jan 1.
* - Resolves the locale's first day of week via
* `Intl.Locale.prototype.weekInfo`.
* - Returns null if `value` or `locale` is invalid.
*
* @param value ISO PlainDate string
* @param locale BCP 47 locale tag (e.g. "fr-FR", "ja-JP", "en-US"), or a preference list of tags (ECMA-402; the first with locale data is read). Required: omitted, or an empty list (which ECMA-402 would resolve to the host default), returns null
* @returns 1-based week-of-month row, or null on invalid input
*
* @example getWeekOfMonth("2024-02-01", "ja-JP") // 1
* @example getWeekOfMonth("2024-02-29", "ja-JP") // 5
* @example getWeekOfMonth("2026-02-01", "pt-BR") // 1
* @example getWeekOfMonth("2026-02-01", "en-GB") // 1
* @example getWeekOfMonth("-271821-04-30", "ja-JP") // 5 (the first representable month; its 1st lies before the range)
* @example getWeekOfMonth("invalid", "hi-IN") // null
* @example getWeekOfMonth("2024-05-12", ["fr-FR", "en-US"]) // 2
*/
function getWeekOfMonth(value, locale) {
if (!isValidDate(value)) return null;
const firstDay = getLocaleFirstDayOfWeek(locale);
if (firstDay === null) return null;
try {
const date = Temporal.PlainDate.from(value);
const dayOfWeek = ((date.dayOfWeek - date.day) % 7 + 7) % 7 + 1;
return monthGridWeekRow({ dayOfWeek }, firstDay, date.day);
} catch {
return null;
}
}
export { getWeekOfMonth };