4.7. Validate ISO 8601 Dates and Times
Problem
You want to match dates and/or times in the official ISO 8601 format,
which is the basis for many standardized date and time formats. For
example, in XML Schema, the built-in date, time, and dateTime types are all based on ISO 8601.
Solution
The following matches a calendar month, e.g., 2008-08. The hyphen is
required:
^([0-9]{4})-(1[0-2]|0[1-9])$| Regex options: None |
| Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
^(?<year>[0-9]{4})-(?<month>1[0-2]|0[1-9])$| Regex options: None |
| Regex flavors: .NET, PCRE 7, Perl 5.10, Ruby 1.9 |
^(?P<year>[0-9]{4})-(?P<month>1[0-2]|0[1-9])$| Regex options: None |
| Regex flavors: PCRE, Python |
Calendar date, e.g., 2008-08-30. The hyphens are optional.
This regex allows YYYY-MMDD and YYYYMM-DD, which do not follow ISO
8601:
^([0-9]{4})-?(1[0-2]|0[1-9])-?(3[0-1]|0[1-9]|[1-2][0-9])$| Regex options: None |
| Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
^(?<year>[0-9]{4})-?(?<month>1[0-2]|0[1-9])-?↵
(?<day>3[0-1]|0[1-9]|[1-2][0-9])$| Regex options: None |
| Regex flavors: .NET, PCRE 7, Perl 5.10, Ruby 1.9 |
Calendar date, e.g., 2008-08-30. The hyphens are optional.
This regex uses a conditional to exclude YYYY-MMDD and YYYYMM-DD.
There is an extra capturing group for the first hyphen:
^([0-9]{4})(-)?(1[0-2]|0[1-9])(?(2)-)(3[0-1]|0[1-9]|[1-2][0-9])$| Regex options: None |
| Regex flavors: .NET, PCRE, Perl, Python |
Calendar date, e.g., 2008-08-30. The hyphens are optional. This regex uses alternation to exclude YYYY-MMDD and ...