1/**2 * Showing a date as text with a pattern: `format(date, "d MMMM yyyy")` is3 * `7 October 2026`. Letters are tokens; text in single quotes is printed as4 * it is (`''` prints one quote); any other character passes through. A5 * letter that is no token is refused, so a typo never prints a wrong date.6 */7import { isValid } from "./parse.ts";8import { utcParts, zonedParts } from "./tz.ts";9import type { ZonedParts } from "./tz.ts";1011/** How `format` shows a date. */12export interface FormatOptions {13 /** The IANA zone to show the date in (`America/New_York`); UTC when left out. */14 readonly timeZone?: string;15}1617const MONTHS = [18 "January",19 "February",20 "March",21 "April",22 "May",23 "June",24 "July",25 "August",26 "September",27 "October",28 "November",29 "December",30];3132const WEEKDAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];3334const pad = (value: number, width: number) => String(value).padStart(width, "0");3536// The English suffix by last digit: 1st, 2nd, 3rd, and th for the rest.37const SUFFIXES = ["th", "st", "nd", "rd"];3839/** A number as an English ordinal: `1st`, `2nd`, `3rd`, `4th`. */40export const ordinal = (value: number): string => `${value}${SUFFIXES[value % 10] ?? "th"}`;4142/** A UTC offset as `Z`, or `+09:00`, `-04:00`, `+05:30`. */43const offsetText = (minutes: number) => {44 if (minutes === 0) {45 return "Z";46 }4748 const sign = minutes < 0 ? "-" : "+";49 const size = Math.abs(minutes);5051 return `${sign}${pad(Math.floor(size / 60), 2)}:${pad(size % 60, 2)}`;52};5354const twelveHour = (hour: number) => hour % 12 || 12;5556/** Each token, and how it shows a date's fields. */57const TOKENS: Readonly<Record<string, (parts: ZonedParts) => string>> = {58 // Year59 yyyy: ({ year }) => pad(year, 4),60 yy: ({ year }) => pad(year % 100, 2),61 // Month62 MMMM: ({ month }) => MONTHS[month - 1] ?? "",63 MMM: ({ month }) => (MONTHS[month - 1] ?? "").slice(0, 3),64 MM: ({ month }) => pad(month, 2),65 M: ({ month }) => String(month),66 // Day of the month67 Do: ({ day }) => ordinal(day),68 dd: ({ day }) => pad(day, 2),69 d: ({ day }) => String(day),70 // Day of the week71 EEEE: ({ weekday }) => WEEKDAYS[weekday - 1] ?? "",72 EEE: ({ weekday }) => (WEEKDAYS[weekday - 1] ?? "").slice(0, 3),73 // Time74 HH: ({ hour }) => pad(hour, 2),75 H: ({ hour }) => String(hour),76 hh: ({ hour }) => pad(twelveHour(hour), 2),77 h: ({ hour }) => String(twelveHour(hour)),78 a: ({ hour }) => (hour < 12 ? "AM" : "PM"),79 mm: ({ minute }) => pad(minute, 2),80 ss: ({ second }) => pad(second, 2),81 SSS: ({ millisecond }) => pad(millisecond, 3),82 // Offset83 XXX: ({ offset }) => offsetText(offset),84};8586// A quoted literal (to its closing quote, or the end), `Do`, a run of one87// letter, or anything that isn't a letter or a quote.88const PIECES = /'(?:[^']|'')*(?:'|$)|Do|([A-Za-z])\1*|[^A-Za-z']+/gu;8990/** One piece of a pattern, shown. */91const show = (piece: string, parts: ZonedParts): string => {92 if (piece.startsWith("'")) {93 return piece === "''"94 ? "'"95 : piece.slice(1, piece.endsWith("'") ? -1 : undefined).replaceAll("''", "'");96 }9798 if (!/^[A-Za-z]/u.test(piece)) {99 return piece;100 }101102 const token = TOKENS[piece];103104 if (token === undefined) {105 throw new RangeError(`format: "${piece}" is not a token; quote literal text, like 'at'`);106 }107108 return token(parts);109};110111/**112 * Shows `date` with `pattern`, in UTC or in `options.timeZone`. Throws a113 * `RangeError` for an invalid date, an unknown token or an unknown zone.114 *115 * | Token | Shows | Example |116 * | --- | --- | --- |117 * | `yyyy`, `yy` | year | `2026`, `26` |118 * | `MMMM`, `MMM`, `MM`, `M` | month | `October`, `Oct`, `10`, `10` |119 * | `Do`, `dd`, `d` | day of the month | `7th`, `07`, `7` |120 * | `EEEE`, `EEE` | day of the week | `Wednesday`, `Wed` |121 * | `HH`, `H`, `hh`, `h`, `a` | hour, 24- and 12-hour, and AM or PM | `14`, `14`, `02`, `2`, `PM` |122 * | `mm`, `ss`, `SSS` | minute, second, millisecond | `05`, `09`, `250` |123 * | `XXX` | UTC offset | `Z`, `+09:00` |124 */125export const format = (date: Date, pattern: string, options: FormatOptions = {}): string => {126 if (!isValid(date)) {127 throw new RangeError("format: the date is invalid");128 }129130 const parts =131 options.timeZone === undefined ? utcParts(date) : zonedParts(date, options.timeZone);132133 return (pattern.match(PIECES) ?? []).map((piece) => show(piece, parts)).join("");134};