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.

45 lines (43 loc) • 2.01 kB
import { resolveRequiredLocale } from "../../internal/resolveLocale.js"; import { cachedFormatter } from "../../internal/formatterCache.js"; // src/plain/locale/getLocaleMeridiems.ts /** * Return a locale's AM/PM (day-period) labels as `[AM-label, PM-label]`. * * - Labels are locale-varying: `en-GB` → `["am", "pm"]`, `zh-CN` → * `["上午", "下午"]`, `ar-SA` → `["ص", "م"]`, `sv-SE` → `["fm", "em"]`, * `en-US` → `["AM", "PM"]`. * - Uses the host runtime's `Intl` data via `Intl.DateTimeFormat`, so output * depends on the runtime's ICU build. * - Returns `[]` if `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 locale BCP 47 locale tag (e.g. "fr-FR", "ar-SA", "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 2-element `[AM-label, PM-label]` array, or `[]` on invalid input * * @example getLocaleMeridiems("ar-EG") // ["ص", "م"] * @example getLocaleMeridiems("en-GB") // ["am", "pm"] * @example getLocaleMeridiems("zh-CN") // ["上午", "下午"] * @example getLocaleMeridiems("not-a-locale-!!") // [] * @example getLocaleMeridiems(["ja-JP", "en-US"]) // ["午前", "午後"] */ function getLocaleMeridiems(locale) { try { const resolvedLocale = resolveRequiredLocale(locale); if (resolvedLocale === null) return []; try { const formatter = cachedFormatter("DateTimeFormat", resolvedLocale, { timeZone: "UTC", hour: "numeric", hour12: true }); return [formatter.formatToParts(0).find((part) => part.type === "dayPeriod")?.value ?? "", formatter.formatToParts(432e5).find((part) => part.type === "dayPeriod")?.value ?? ""]; } catch { return []; } } catch { return []; } } export { getLocaleMeridiems };