UNPKG

@thi.ng/date

Version:

Datetime types, relative dates, math, iterators, composable formatters, locales

54 lines (53 loc) 1.44 kB
import { isString } from "@thi.ng/checks/is-string"; import { EN_SHORT } from "./i18n/en.js"; const __prepLocale = (spec) => { const locale = { sepED: " ", sepDM: "/", sepMY: "/", sepHM: ":", date: ["E", "/ED", "d", "/DM", "MMM", "/MY", "yyyy"], time: ["H", "/HM", "mm"], ...spec }; !locale.dateTime && (locale.dateTime = [...locale.date, ", ", ...locale.time]); return locale; }; const setLocale = (locale) => LOCALE = __prepLocale(locale); const withLocale = (locale, fn) => { const old = LOCALE; setLocale(locale); try { const res = fn(); setLocale(old); return res; } catch (e) { setLocale(old); throw e; } }; let LOCALE = __prepLocale(EN_SHORT); const weekdayNames = () => LOCALE.days.slice(); const monthNames = () => LOCALE.months.slice(); const units = (x, unit, isDativ = false, unitsOnly = false) => { unit = isString(unit) ? LOCALE.units[unit] : unit; const res = x > 1 || x === 0 ? isDativ ? unit.pd || unit.p : unit.p : isDativ ? unit.sd || unit.s : unit.s; return unitsOnly ? res : `${x} ${res}`; }; const unitsLessThan = (x, unit, isDativ = false) => `${LOCALE.less.replace("%s", String(x))} ${units( Math.max(x, 1), unit, isDativ, true )}`; const tense = (sign, res) => (sign < 0 ? LOCALE.past : LOCALE.future).replace("%s", res); export { LOCALE, monthNames, setLocale, tense, units, unitsLessThan, weekdayNames, withLocale };