Reputation: 318
I want to validate the date- time format which is like '2014-08-29T06:44:03Z' for this i am looking for a reg ex.
Tried few combinations but those did not work for me.
Upvotes: 18
Views: 33089
Reputation: 3694
Took @Will Jones 's answer as an extension to OP's requirements. This should match optional local time specifier and milliseconds, i.e.
2020-04-20T09:32:28+00:00
2020-04-20T09:32:28.123Z
both match.
Further positive and negative test cases written: https://regex101.com/r/ufFBTA/2
\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2]\d|3[0-1])T(?:[0-1]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+|)(?:Z|(?:\+|\-)(?:\d{2}):?(?:\d{2}))
Upvotes: 7
Reputation: 6024
Try this regex
\b[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z\b
There:
\b
- word boundary, to check what for example '92014-08-29T06:44:03Z' is invalid
[0-9]{n}
- match number with n digits
If a string must contain only date-time and no other chars, then use:
^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$
Upvotes: 22
Reputation: 171
The following regex accepts an ISO-8601 UTC date time string ensuring:
format: YYYY-MM-DDThh:mm:ssZ
example: 2016-07-08T12:30:00Z
where:
YYYY = 0000 to 9999
MM = 01 to 12
DD = 01 to 31
hh = 00 to 23
mm = 00 to 59
ss = 00 to 59
\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2]\d|3[0-1])T(?:[0-1]\d|2[0-3]):[0-5]\d:[0-5]\dZ
You can test it out here: https://regex101.com/r/jE4cE4/1
Upvotes: 17
Reputation: 6604
rims answer will definitely work, here are a few more examples.
A little more brevity:
\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z
A little more precision:
\d{4}-[01]{1}\d{1}-[0-3]{1}\d{1}T[0-2]{1}\d{1}:[0-6]{1}\d{1}:[0-6]{1}\d{1}Z
Of course, you can write more advanced expressions that are more efficient than this using forward and back referencing to really ensure you have a 100% validated match for allowable combinations, etc...
Upvotes: 2