Skip to main content
hank-builds.com

Date (YYYY-MM-DD) regex

Matches dates in ISO 8601 format.

/\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])/g

What it matches

A four-digit year, a month of 01-12 and a day of 01-31, hyphen separated and zero padded, which is the calendar-date form of ISO 8601. The month and day alternations do the range checking, so 2024-13-01 and 2024-01-32 are rejected outright rather than matched and left for later validation.

Railroad diagram

Read left to right. Every path through the diagram is a string the pattern accepts.

{4} \d "-" "0" [1-9] "1" [0-2] "-" "0" [1-9] [12] \d "3" [01]

Drag to pan. Ctrl+scroll to zoom.

Breakdown

gFind all matches instead of stopping after the first
\d{4}Digit (0-9), exactly 4 times
-Literal "-"
0Literal "0"
[1-9]Match one of: Literal "1"–Literal "9"
1Literal "1"
[0-2]Match one of: Literal "0"–Literal "2"
-Literal "-"
0Literal "0"
[1-9]Match one of: Literal "1"–Literal "9"
[12]Match one of: Literal "1", Literal "2"
\dDigit (0-9)
3Literal "3"
[01]Match one of: Literal "0", Literal "1"

Test cases

Matches

  • 2024-01-15
  • 2024-12-31
  • 1999-06-01

Does not match

  • 2024-13-01
  • 2024-1-5
  • 15/01/2024

Caveats

It checks ranges, not the calendar. 2024-02-31 and 2023-02-29 both match even though neither date exists, because a regex cannot count the days in a month or work out leap years. Treat a match as a well-formed date string and hand it to a date library to learn whether it is a real day.

More dates & times patterns

Test this against your own input in the regex tester, browse the full pattern library, or check the syntax cheat sheet.