UNPKG

@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.

44 lines (42 loc) • 2.13 kB
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/getWeeksInMonth.ts /** * Return the number of calendar-grid rows (4, 5, or 6) `value`'s month * spans, using `locale`'s first day of week. * * - The count depends on which day the week starts — the same month can * span 4, 5, or 6 rows depending on locale (e.g. February 2026 is 4 * rows starting Sunday but 5 rows starting Monday). * - The count is the UTS #35 week of month (`W`) of the month's last day, with the locale's first * day of week and minimal days fixed at 1 (see `getWeekOfMonth`). * - 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 number of week-rows the month spans (4-6), or null on invalid input * * @example getWeeksInMonth("2024-02-15", "pt-BR") // 5 * @example getWeeksInMonth("2026-02-15", "ja-JP") // 4 * @example getWeeksInMonth("2026-02-15", "en-GB") // 5 * @example getWeeksInMonth("-271821-04-19", "ja-JP") // 5 (the first representable month; its 1st lies before the range) * @example getWeeksInMonth("invalid", "hi-IN") // null * @example getWeeksInMonth("2024-06-15", ["ja-JP", "fr-FR"]) // 6 */ function getWeeksInMonth(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.daysInMonth); } catch { return null; } } export { getWeeksInMonth };