Regex for a YYYY-MM-DD date

A regular expression for ISO 8601 calendar dates such as 2023-11-14, what it can and cannot check, and the short extra step that rejects dates like 31 February.

//

Matches

This tool runs in your browser. We never send what you type or paste to a server.

The pattern

/^[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])$/

YYYY-MM-DD is the calendar date format of ISO 8601 and of RFC 3339, which most APIs and the HTML <input type="date"> value use. It sorts correctly as plain text and cannot be misread as day-month or month-day. The pattern checks the shape and the ranges of the month and the day.

The tester at the top of this page is loaded with this pattern and the examples below, one per line. It adds the m flag so that ^ and $ apply to each line, and g to show every match. Edit either box to try your own input.

How it works, token by token

PartMeaning
^Start of the string.
[0-9]{4}A four-digit year, 0000 to 9999.
-A literal hyphen.
(?:0[1-9]|1[0-2])The month, 01 to 12, always two digits.
-Another hyphen.
(?:0[1-9]|[12][0-9]|3[01])The day, 01 to 31, always two digits.
$End of the string.

What it matches and what it rejects

InputResultWhy
2023-11-14matchesAn ordinary date.
2024-02-29matchesA leap day.
1999-12-31matchesAny year from 0000 to 9999.
2023-02-31matchesAccepted: the pattern does not know how long each month is.
2023-13-01rejectedMonth 13.
2023-00-10rejectedMonth 00.
2023-11-32rejectedDay 32.
2023-1-5rejectedMonths and days need two digits.
23-11-14rejectedA two-digit year.
2023/11/14rejectedSlashes.
20231114rejectedThe basic format without hyphens.
2023-11-14T22:13:20ZrejectedA date and time: see below.

Checking that the date exists

A regex can be made to understand month lengths and even leap years, but the result is long and hard to review. It is simpler to let the pattern check the format and the date library check the calendar:

const DATE = /^[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])$/;

function isRealDate(s) {
  if (!DATE.test(s)) return false;
  const [y, m, d] = s.split('-').map(Number);
  const dt = new Date(0);
  dt.setUTCFullYear(y, m - 1, d); // not Date.UTC, which reads the years 0 to 99 as 1900 to 1999
  return dt.getUTCFullYear() === y && dt.getUTCMonth() === m - 1 && dt.getUTCDate() === d;
}

console.log(isRealDate('2024-02-29'), isRealDate('2023-02-29'));  // → true false
console.log(isRealDate('0099-01-01'));                            // → true
import re
from datetime import date

DATE = re.compile(r'[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])')

def is_real_date(s):
    if not DATE.fullmatch(s):
        return False
    try:
        date.fromisoformat(s)
        return True
    except ValueError:
        return False

print(is_real_date('2024-02-29'), is_real_date('2023-02-29'))  # → True False
print(date.fromisoformat('20231114'))  # → 2023-11-14   Python 3.11+ also reads the basic format

Do not use JavaScript's Date parser on its own for this. Given an impossible date in this format, Node.js 24 rolls it over into the next month instead of failing:

console.log(new Date('2023-02-31').toISOString());  // → 2023-03-03T00:00:00.000Z

And Python's date.fromisoformat is not strict enough on its own either: since Python 3.11 it also accepts other ISO 8601 forms such as 20231114 (see the datetime documentation), so run the pattern first if you need exactly YYYY-MM-DD.

Day-first dates

For DD/MM/YYYY, as used in the UK, the same parts go in a different order, with the slashes escaped for JavaScript:

/^(?:0[1-9]|[12][0-9]|3[01])\/(?:0[1-9]|1[0-2])\/[0-9]{4}$/
InputResultWhy
14/11/2023matchesDay first, as in the UK.
01/02/2024matches1 February in the UK, 2 January in the US: the pattern cannot tell.
11/14/2023rejectedUS order: there is no month 14.
14-11-2023rejectedHyphens.
1/2/2024rejectedTwo digits each.

A pattern cannot tell whether 01/02/2024 means 1 February or 2 January; only the context can. Where you control the format, use YYYY-MM-DD, or a date picker that produces it.

Dates with a time

To accept a full RFC 3339 timestamp such as 2023-11-14T22:13:20Z, append a time and a zone after the date part: T, the time pattern with seconds, optional fractions of a second ((?:\.[0-9]+)?) and either Z or an offset such as +01:00. At that point a parser is again the better tool, because it also converts the result into a value you can compare. For Unix timestamps and how they relate to ISO dates, see ISO 8601 against epoch time.

In JavaScript, Python, PHP and C#

JavaScript

const re = /^[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])$/;
console.log(re.test('2023-11-14')); // → true
console.log(re.test('2023-13-01')); // → false

Python

import re

pattern = re.compile(r'[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])')
print(bool(pattern.fullmatch('2023-11-14')))  # → True
print(bool(pattern.fullmatch('2023-13-01')))  # → False

PHP

<?php
$pattern = '/^[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])$/D';
echo preg_match($pattern, '2023-11-14'), "\n"; // → 1
echo preg_match($pattern, '2023-13-01'), "\n"; // → 0

C#

using System;
using System.Text.RegularExpressions;

var pattern = new Regex(@"^[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])\z");
Console.WriteLine(pattern.IsMatch("2023-11-14")); // → True
Console.WriteLine(pattern.IsMatch("2023-13-01")); // → False

Each version checks the whole string. JavaScript's $ only matches at the very end, but Python, PHP and .NET also let $ match just before a final line break, so "abc\n" could slip through. The Python version uses re.fullmatch (so the ^ and $ are dropped), PHP adds the D modifier, and C# ends with \z.

The JavaScript, Python and C# examples are run before each update and their output is compared with the comments. PHP is not installed on our build machine, so the PHP version is checked against the PCRE pattern modifier documentation, and its string literal is checked to hand PHP exactly the pattern tested here.

Questions

What is the regex for YYYY-MM-DD?

^[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])$ checks a four-digit year, a month from 01 to 12 and a day from 01 to 31. Check the real calendar date with a date library afterwards.

Why does my date regex accept 2023-02-31?

Because it checks each part separately and does not know month lengths. Parse the date and compare the year, month and day you get back with the ones you put in.

How do I match a date anywhere in a string?

Replace ^ and $ with \b, as in \b[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])\b, and use the g flag to find every date.