A set of regular expressions to match ISO 8601 years, weeks, dates, times, and datetimes with optional time zone.
Year And Month
This regex matches a calendar month like 2020-12.
/^([0-9]{4})-(1[0-2]|0[1-9])$/
Dates
This regex matches a calendar date like 2020-12-29 and 20201229.
/^([0-9]{4})-?(1[0-2]|0[1-9])-?(3[01]|0[1-9]|[12][0-9])$/
Date with optional time zone
This regex matches a calendar date with an optional time zone 2020-12-29-07:00.
/^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])(Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$/
Weeks
This regex matches Week of the year like 2020-W40.
/^([0-9]{4})-?W(5[0-3]|[1-4][0-9]|0[1-9])$/
Hours and Minutes
This regex matches ISO 8601 time format (Hours and Minutes) like 19:30.
/^(2[0-3]|[01][0-9]):?([0-5][0-9])$/
Hours, minutes, and seconds
This regex matches ISO 8601 time format (Hours, minutes, and seconds) like 19:30:45.
/^(2[0-3]|[01][0-9]):?([0-5][0-9]):?([0-5][0-9])$/
Hours, minutes, and seconds with timezone
This regex matches ISO 8601 time format (Hours, minutes, and seconds with timezone) like 19:30:45-05:00.
/^(2[0-3]|[01][0-9]):?([0-5][0-9]):?([0-5][0-9])(Z|[+-](?:2[0-3]|[01][0-9])(?::?(?:[0-5][0-9]))?)$/
Date And Time
This regex matches ISO 8601 date with hours, minutes, and seconds like 2020-12-29 19:30:45 or 20201229 193045.
/^([0-9]{4})-?(1[0-2]|0[1-9])-?(3[01]|0[1-9]|[12][0-9]) (2[0-3]|[01][0-9]):?([0-5][0-9]):?([0-5][0-9])$/
Date And Time with optional time zone
This regex matches ISO 8601 date with optional fractional seconds and time zone like 2020-12-29T19:30:45 or 2020-12-29T19:30:45.123Z.
/^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(\.[0-9]+)?(Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$/
See Also:
- ISO 8601 Date Regular Expression
- RFC 2822 Date Format Regular Expression
- Regular Expression To Match Month Name