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.

60 lines (58 loc) • 2.1 kB
import { Temporal } from "./temporal.js"; // src/internal/swiftDate.ts /** The first year SWIFT accepts in a value date (Standards MT General Information, 2025, §6.3.1). */ const SWIFT_VALUE_DATE_FIRST_YEAR = 2001; /** The last year SWIFT accepts in a value date; any other year is error T50 (same, §6.3.6). */ const SWIFT_VALUE_DATE_LAST_YEAR = 2060; const SWIFT_DATE = /^([0-9]{2})([0-9]{2})([0-9]{2})$/; /** Read the fields of a `YYMMDD` value, or null when the shape does not match. */ function readSwiftDateFields(value) { const match = SWIFT_DATE.exec(value); if (match === null) return null; const [, yy, mm, dd] = match; return { yy: Number(yy), month: Number(mm), day: Number(dd) }; } /** * The year SWIFT's value-date rule gives a two-digit `yy`, or null for error T50. * §6.3.6: a `YY` from 01 through 60 is allowed, and §6.3.1 reads it as 20`YY` (2001 to 2060); * any other `YY`, `00` and `61`–`99` included, is error T50. */ function swiftValueDateYear(yy) { const year = 2e3 + yy; return year < 2001 || year > 2060 ? null : year; } function pad2(n) { return String(n).padStart(2, "0"); } /** Write `YYMMDD` from a year 2001–2060, a month 1–12 and a day 1–31. The caller passes valid values. */ function writeSwiftDate(year, month, day) { return pad2(year % 100) + pad2(month) + pad2(day); } /** * The core of `parseSwiftDate` and `isValidSwiftDate`: the ISO date a SWIFT `YYMMDD` value date * names, or `""`. Never throws. * * @example readSwiftDate("240315") // "2024-03-15" * @example readSwiftDate("240230") // "" */ function readSwiftDate(value) { try { if (typeof value !== "string") return ""; const fields = readSwiftDateFields(value); if (fields === null) return ""; const year = swiftValueDateYear(fields.yy); if (year === null) return ""; return Temporal.PlainDate.from({ year, month: fields.month, day: fields.day }, { overflow: "reject" }).toString(); } catch { return ""; } } export { SWIFT_VALUE_DATE_FIRST_YEAR, SWIFT_VALUE_DATE_LAST_YEAR, readSwiftDate, readSwiftDateFields, swiftValueDateYear, writeSwiftDate };