@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.19 kB
JavaScript
import { plainDateOf } from "../../internal/inputChecks.js";
import { getLocaleFirstDayOfWeek } from "../../internal/getLocaleFirstDayOfWeek.js";
import { localeStartOfWeek } from "../../internal/plainDateSteps.js";
// src/plain/calculate/getLocaleStartOfWeek.ts
/**
* Return the start of the week containing `value`, using `locale`'s
* first day of week (e.g. fr-FR: Monday, ja-JP: Sunday).
*
* - Resolves the locale's first day of week via
* `Intl.Locale.prototype.weekInfo`.
* - Falls back to Monday if the runtime's `weekInfo` data doesn't resolve
* a first day for the locale.
* - Distinct from `startOfDate(value, "week", { weekStartsOn })`, which
* takes an explicit ISO-biased `weekStartsOn` option instead of deriving
* it from a locale.
* - Returns "" if `value` is invalid or `locale` is not a well-formed BCP 47 tag
* (ECMA-402 `IsWellFormedLanguageTag`).
* A well-formed tag with no matching locale data is not an error: it falls back to the host's
* default locale, as ECMA-402 `ResolveLocale` requires.
*
* @param value ISO 8601 date 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 ""
* @returns ISO 8601 date string for the start of `value`'s locale-relative week, or "" on invalid input
*
* @example getLocaleStartOfWeek("2024-02-29", "ja-JP") // "2024-02-25" (Sunday)
* @example getLocaleStartOfWeek("2024-02-29", "fr-FR") // "2024-02-26" (Monday)
* @example getLocaleStartOfWeek("invalid-date", "hi-IN") // ""
* @example getLocaleStartOfWeek("2024-02-29", "not-a-locale-!!") // ""
* @example getLocaleStartOfWeek("2024-05-15", ["pt-BR", "fr-FR"]) // "2024-05-12" (pt-BR, the first listed locale, starts weeks on Sunday)
*/
function getLocaleStartOfWeek(value, locale) {
const source = plainDateOf(value);
if (source === null) return "";
const firstDay = getLocaleFirstDayOfWeek(locale);
if (firstDay === null) return "";
try {
return localeStartOfWeek(source, firstDay).toString();
} catch {
return "";
}
}
export { getLocaleStartOfWeek };