Skip to content

Instantly share code, notes, and snippets.

View aborchew's full-sized avatar
🌐

Ari Borchew aborchew

🌐
View GitHub Profile
@aborchew
aborchew / ISODateString.ts
Last active October 5, 2023 15:55
ISODateString Type and Type Guard
// Validate the formatting of an ISO 8601 Date String
// The ISODateString Type will ensure that the days do not exceed those in the month, although YYYY-02-29 will always be valid
// The isISODateString Type Guard will validate formatting and ensure that the date is valid, also taking into account leap years
// If using a Regular Expression engine that supports Conditionals (JavaScript does not), this shorter expression does the same thing
// ^(?:(?<leap>\d{2}[02468][048]|^\d{2}[13579][26]|[048])|\d{4})-\b(?<d29>(?(leap)02|(?<d30>(?<d31>01|03|05|07|08|10|12)|(?:04|06|09|11))))|02\b-\b(?:0[1-9]|1[0-9]|(?(d31)(2[0-9]|30|31)|(?(d30)(2[0-9]|30)|(?(d29)2[0-9]|2[0-8]))))\b
// And the same without named groups:
// ^(?:(\d{2}[02468][048]|^\d{2}[13579][26]|[048])|\d{4})-\b((?(1)02|((01|03|05|07|08|10|12)|(?:04|06|09|11))))|02\b-\b(?:0[1-9]|1[0-9]|(?(4)(2[0-9]|30|31)|(?(3)(2[0-9]|30)|(?(2)2[0-9]|2[0-8]))))\b
import dayjs = require('dayjs');