How to match ISO8601 Date/Time?

ISO 8601 is a standard describing the exchange of date and time related data. This standard is used in most software applications for deserializing and serializing dates and times. It is a super broad standard and these regular expressions don’t even begin to cover all the valid formats.

These regular expressions will be best used for things like client-side validation and then rely on your actual ISO8601 parser to determine what is “valid” or not. After all, it doesn’t matter if your string is valid if you cannot parse it with DateTime::createFromFormat(DateTime::ISO8601, '2016-07-27T19:30:00Z').


Calendar Month

Example: 2018-10

Regex: ^([0-9]{4})-(1[0-2]|0[1-9])$

Calendar Dates

Example: 2018-10-31

Regex: ^(([12]\d{3})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))$


Hours and Minutes

Example: 10:32

Regex: ^(2[0-3]|[01][0-9]):([0-5][0-9])$

Hours, Minutes and Seconds

Example: 10:32:54

Regex: ^(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])$

Hours, Minutes and Seconds with TimeZone

Example: 10:21:59+08:00 or 10:21:59Z

Regex: ^(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

Example: 2008-10-30 17:21:59

Regex: ^([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])$



The latest tutorials sent straight to your inbox.