Skip to content
Myr

parse.ts

This file

Path

src/parse.ts

177 lines · 5.6 KiB · TypeScript

Last changed by

parse-iso-weekanswered by oscarbf199ee

History of this file

Take it

landed by oscabriel6a2b761

line 1
1/**
2 * Reading ISO 8601 text. `parseISO` reads calendar dates, ordinal dates and3 * week dates, with an optional time and UTC offset, and never throws: text it4 * can't read gives an invalid date, which `isValid` tells apart.

landed by oscabriel6a2b761

lines 5–6
5 */
6import {7 MS_PER_DAY,

landed by oscabriel6a2b761

lines 8–12
8 MS_PER_HOUR,
9 MS_PER_MINUTE,10 MS_PER_SECOND,11 daysInMonth,12 daysInYear,13 isoWeekday,

landed by oscabriel6a2b761

lines 14–32
14 utcMidnight,
15} from "./calendar.ts";1617/** A date that stands for no instant: what `parseISO` gives for text it can't read. */18export const invalidDate = (): Date => new Date(Number.NaN);1920/** Whether `date` stands for an instant (an invalid date doesn't). */21export const isValid = (date: Date): boolean => !Number.isNaN(date.getTime());2223/** The date forms `parseISO` reads, extended and basic. */24const CALENDAR_DATES = [25 /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/u,26 /^(?<year>\d{4})(?<month>\d{2})(?<day>\d{2})$/u,27 /^(?<year>\d{4})-(?<month>\d{2})$/u,28 /^(?<year>\d{4})$/u,29];3031const ORDINAL_DATE = /^(?<year>\d{4})-?(?<ordinal>\d{3})$/u;3233/** The week date forms, extended and basic; a week with no day is its Monday. */34const WEEK_DATES = [35 /^(?<year>\d{4})-W(?<week>\d{2})(?:-(?<weekday>\d))?$/u,36 /^(?<year>\d{4})W(?<week>\d{2})(?<weekday>\d)?$/u,37];38

landed by oscabriel6a2b761

lines 39–52
39const TIME =
40 /^(?<hour>\d{2})(?::(?<minute>\d{2})(?::(?<second>\d{2})(?:[.,](?<fraction>\d{1,9}))?)?)?(?<offset>Z|[+-]\d{2}(?::?\d{2})?)?$/u;4142const OFFSET = /^(?<sign>[+-])(?<hours>\d{2}):?(?<minutes>\d{2})?$/u;4344const whole = (digits: string | undefined, fallback = 0): number =>45 digits === undefined ? fallback : Number(digits);4647/** A calendar date, as the instant it starts in UTC; `undefined` when it isn't a real day. */48const calendarDay = (year: number, month: number, day: number): number | undefined =>49 month >= 1 && month <= 12 && day >= 1 && day <= daysInMonth(year, month)50 ? utcMidnight(year, month, day)51 : undefined;5253/**54 * The instant ISO week 1 of `year` starts in UTC: the Monday of the week55 * holding January 4, which is the first week with a Thursday in the year.56 */57const firstWeekMonday = (year: number): number => {58 const january4 = utcMidnight(year, 1, 4);5960 return january4 - (isoWeekday(new Date(january4)) - 1) * MS_PER_DAY;61};6263/** How many ISO weeks `year` has: 52, or 53 when its weeks don't fit in 52. */64const weeksInYear = (year: number): number =>65 (firstWeekMonday(year + 1) - firstWeekMonday(year)) / (7 * MS_PER_DAY);6667/** A week date, as the instant its day starts in UTC; `undefined` when the year has no such day. */68const weekDay = (year: number, week: number, weekday: number): number | undefined =>69 week >= 1 && week <= weeksInYear(year) && weekday >= 1 && weekday <= 770 ? firstWeekMonday(year) + ((week - 1) * 7 + weekday - 1) * MS_PER_DAY71 : undefined;72

landed by oscabriel6a2b761

lines 73–91
73/** The start of the day the date part names, in epoch milliseconds. */
74const readDate = (text: string): number | undefined => {75 for (const form of CALENDAR_DATES) {76 const groups = form.exec(text)?.groups;7778 if (groups !== undefined) {79 return calendarDay(whole(groups.year), whole(groups.month, 1), whole(groups.day, 1));80 }81 }8283 const ordinal = ORDINAL_DATE.exec(text)?.groups;8485 if (ordinal !== undefined) {86 const year = whole(ordinal.year);87 const day = whole(ordinal.ordinal);8889 return day >= 1 && day <= daysInYear(year) ? utcMidnight(year, 1, day) : undefined;90 }9192 for (const form of WEEK_DATES) {93 const groups = form.exec(text)?.groups;9495 if (groups !== undefined) {96 return weekDay(whole(groups.year), whole(groups.week), whole(groups.weekday, 1));97 }98 }99

landed by oscabriel6a2b761

lines 100–155
100 return undefined;
101};102103/** A UTC offset (`Z`, `+09:00`, `-0330`, `+05`) in minutes east of UTC. */104const readOffset = (text: string | undefined): number | undefined => {105 if (text === undefined || text === "Z") {106 return 0;107 }108109 const groups = OFFSET.exec(text)?.groups;110111 if (groups === undefined) {112 return undefined;113 }114115 const hours = whole(groups.hours);116 const minutes = whole(groups.minutes);117118 if (hours > 23 || minutes > 59) {119 return undefined;120 }121122 return (groups.sign === "-" ? -1 : 1) * (hours * 60 + minutes);123};124125/** How far past midnight the time part is, in UTC milliseconds (its offset taken off). */126const readTime = (text: string): number | undefined => {127 const groups = TIME.exec(text)?.groups;128129 if (groups === undefined) {130 return undefined;131 }132133 const hour = whole(groups.hour);134 const minute = whole(groups.minute);135 const second = whole(groups.second);136 const offset = readOffset(groups.offset);137138 if (hour > 23 || minute > 59 || second > 59 || offset === undefined) {139 return undefined;140 }141142 // Digits past the millisecond are dropped, not rounded.143 const millisecond = whole((groups.fraction ?? "").padEnd(3, "0").slice(0, 3));144145 return (146 hour * MS_PER_HOUR +147 minute * MS_PER_MINUTE +148 second * MS_PER_SECOND +149 millisecond -150 offset * MS_PER_MINUTE151 );152};153154/**155 * Reads ISO 8601 text: a date (`2026-10-07`, `20261007`, `2026-10`, `2026`,156 * the ordinal `2026-280`, or the week date `2026-W41-3`, `2026W413` or157 * `2026-W41` for the week's Monday), then optionally `T` and a time158 * (`14:30`, `14:30:15`, `14:30:15.250`) with a UTC offset (`Z`, `+09:00`).159 * Text with no offset is read as UTC. Anything else, or a day that doesn't160 * exist (`2026-02-29`, `2027-W53`), gives an invalid date.

landed by oscabriel6a2b761

lines 161–177
161 */
162export const parseISO = (text: string): Date => {163 const [datePart = "", timePart, ...rest] = text.trim().split("T");164 const day = readDate(datePart);165166 if (day === undefined || rest.length > 0) {167 return invalidDate();168 }169170 if (timePart === undefined) {171 return new Date(day);172 }173174 const time = readTime(timePart);175176 return time === undefined ? invalidDate() : new Date(day + time);177};