parse.ts
This file
Path
examples/datekit/src/parse.ts
140 lines · 4.2 KiB · TypeScript
Last changed by
Not known.
History of this fileTake it
The walk stopped after 200 commits: lines older than 678c8b8 point at it.
Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1–140why, one step back1/**2 * Reading ISO 8601 text. `parseISO` reads calendar dates and ordinal dates,3 * with an optional time and UTC offset, and never throws: text it can't read4 * gives an invalid date, which `isValid` tells apart.5 */6import {7 MS_PER_HOUR,8 MS_PER_MINUTE,9 MS_PER_SECOND,10 daysInMonth,11 daysInYear,12 utcMidnight,13} from "./calendar.ts";1415/** A date that stands for no instant: what `parseISO` gives for text it can't read. */16export const invalidDate = (): Date => new Date(Number.NaN);1718/** Whether `date` stands for an instant (an invalid date doesn't). */19export const isValid = (date: Date): boolean => !Number.isNaN(date.getTime());2021/** The date forms `parseISO` reads, extended and basic. */22const CALENDAR_DATES = [23 /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/u,24 /^(?<year>\d{4})(?<month>\d{2})(?<day>\d{2})$/u,25 /^(?<year>\d{4})-(?<month>\d{2})$/u,26 /^(?<year>\d{4})$/u,27];2829const ORDINAL_DATE = /^(?<year>\d{4})-?(?<ordinal>\d{3})$/u;3031const TIME =32 /^(?<hour>\d{2})(?::(?<minute>\d{2})(?::(?<second>\d{2})(?:[.,](?<fraction>\d{1,9}))?)?)?(?<offset>Z|[+-]\d{2}(?::?\d{2})?)?$/u;3334const OFFSET = /^(?<sign>[+-])(?<hours>\d{2}):?(?<minutes>\d{2})?$/u;3536const whole = (digits: string | undefined, fallback = 0): number =>37 digits === undefined ? fallback : Number(digits);3839/** A calendar date, as the instant it starts in UTC; `undefined` when it isn't a real day. */40const calendarDay = (year: number, month: number, day: number): number | undefined =>41 month >= 1 && month <= 12 && day >= 1 && day <= daysInMonth(year, month)42 ? utcMidnight(year, month, day)43 : undefined;4445/** The start of the day the date part names, in epoch milliseconds. */46const readDate = (text: string): number | undefined => {47 for (const form of CALENDAR_DATES) {48 const groups = form.exec(text)?.groups;4950 if (groups !== undefined) {51 return calendarDay(whole(groups.year), whole(groups.month, 1), whole(groups.day, 1));52 }53 }5455 const ordinal = ORDINAL_DATE.exec(text)?.groups;5657 if (ordinal !== undefined) {58 const year = whole(ordinal.year);59 const day = whole(ordinal.ordinal);6061 return day >= 1 && day <= daysInYear(year) ? utcMidnight(year, 1, day) : undefined;62 }6364 return undefined;65};6667/** A UTC offset (`Z`, `+09:00`, `-0330`, `+05`) in minutes east of UTC. */68const readOffset = (text: string | undefined): number | undefined => {69 if (text === undefined || text === "Z") {70 return 0;71 }7273 const groups = OFFSET.exec(text)?.groups;7475 if (groups === undefined) {76 return undefined;77 }7879 const hours = whole(groups.hours);80 const minutes = whole(groups.minutes);8182 if (hours > 23 || minutes > 59) {83 return undefined;84 }8586 return (groups.sign === "-" ? -1 : 1) * (hours * 60 + minutes);87};8889/** How far past midnight the time part is, in UTC milliseconds (its offset taken off). */90const readTime = (text: string): number | undefined => {91 const groups = TIME.exec(text)?.groups;9293 if (groups === undefined) {94 return undefined;95 }9697 const hour = whole(groups.hour);98 const minute = whole(groups.minute);99 const second = whole(groups.second);100 const offset = readOffset(groups.offset);101102 if (hour > 23 || minute > 59 || second > 59 || offset === undefined) {103 return undefined;104 }105106 // Digits past the millisecond are dropped, not rounded.107 const millisecond = whole((groups.fraction ?? "").padEnd(3, "0").slice(0, 3));108109 return (110 hour * MS_PER_HOUR +111 minute * MS_PER_MINUTE +112 second * MS_PER_SECOND +113 millisecond -114 offset * MS_PER_MINUTE115 );116};117118/**119 * Reads ISO 8601 text: a date (`2026-10-07`, `20261007`, `2026-10`, `2026`,120 * or the ordinal `2026-280`), then optionally `T` and a time (`14:30`,121 * `14:30:15`, `14:30:15.250`) with a UTC offset (`Z`, `+09:00`). Text with122 * no offset is read as UTC. Anything else, or a day that doesn't exist123 * (`2026-02-29`), gives an invalid date.124 */125export const parseISO = (text: string): Date => {126 const [datePart = "", timePart, ...rest] = text.trim().split("T");127 const day = readDate(datePart);128129 if (day === undefined || rest.length > 0) {130 return invalidDate();131 }132133 if (timePart === undefined) {134 return new Date(day);135 }136137 const time = readTime(timePart);138139 return time === undefined ? invalidDate() : new Date(day + time);140};