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.

70 lines (68 loc) • 2.23 kB
import { Temporal } from "./temporal.js"; import { isOptionsArgument } from "./isObject.js"; import { twoDigitYear } from "./twoDigitYear.js"; import { readYearWindowStart } from "./yearWindowStart.js"; // src/internal/ssimDate.ts /** The SSIM month letters, January first: the first three letters of each English month name, upper case. */ const SSIM_MONTH_LETTERS = [ "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" ]; const SSIM_DATE = new RegExp(`^([0-9]{2})(${SSIM_MONTH_LETTERS.join("|")})([0-9]{2})$`); /** Read the fields of a `DDMMMYY` value, or null when the shape does not match. */ function readSsimDateFields(value) { const match = SSIM_DATE.exec(value); if (match === null) return null; const [, dd, mmm, yy] = match; return { day: Number(dd), month: SSIM_MONTH_LETTERS.indexOf(mmm) + 1, yy: Number(yy) }; } function pad2(n) { return String(n).padStart(2, "0"); } /** Write `DDMMMYY` from a day 1–31, a month 1–12 and a year 0–99. The caller passes valid values. */ function writeSsimDate(day, month, yy) { return pad2(day) + SSIM_MONTH_LETTERS[month - 1] + pad2(yy); } /** * The core of `parseSsimDate` and `isValidSsimDate`: the ISO date an SSIM `DDMMMYY` names, with * its two-digit year placed by the caller's `yearWindow` option. Never throws. * * @param value an SSIM date such as `15MAR24` * @param options how the two-digit year is placed * @returns the ISO 8601 date, or `""` when `value` or `options` is invalid * * @example readSsimDate("15MAR24", { yearWindow: 2000 }) // "2024-03-15" * @example readSsimDate("32MAR24", { yearWindow: 2000 }) // "" */ function readSsimDate(value, options) { try { if (typeof value !== "string") return ""; if (!isOptionsArgument(options)) return ""; const fields = readSsimDateFields(value); if (fields === null) return ""; const windowStart = readYearWindowStart(options); if (windowStart === null) return ""; return Temporal.PlainDate.from({ year: twoDigitYear(fields.yy, windowStart), month: fields.month, day: fields.day }, { overflow: "reject" }).toString(); } catch { return ""; } } export { SSIM_MONTH_LETTERS, readSsimDate, readSsimDateFields, writeSsimDate };