Forum Discussion
Hi NadiaRanalli
to pattern match a string in an assertion typically regex is used and for simple to even complex strings regex does the job perfectly
HOWEVER - pattern matching regex against datetimes is quite difficult as it's more difficult than you think to ensure the pattern you specify covers off all illegal dates in perpetuity.
The following stackoverflow link -->. https://stackoverflow.com/questions/1057716/regular-expression-to-validate-a-timestamp gives you some idea how complicated it can be to ensure you cover off all the illegals.
Via stackoverflow, Okipa came up with the following (gotta give credit where it's due! ;))
((((19|20)([2468][048]|[13579][26]|0[48])|2000)-02-29|((19|20)[0-9]{2}-(0[4678]|1[02])-(0[1-9]|[12][0-9]|30)|(19|20)[0-9]{2}-(0[1359]|11)-(0[1-9]|[12][0-9]|3[01])|(19|20)[0-9]{2}-02-(0[1-9]|1[0-9]|2[0-8])))\s([01][0-9]|2[0-3]):([012345][0-9]):([012345][0-9]))
I made a couple of tweaks to match your specific value so changed Okipa's regex to the following:
((((19|20)([2468][048]|[13579][26]|0[48])|2000)-02-29|((19|20)[0-9]{2}-(0[4678]|1[02])-(0[1-9]|[12][0-9]|30)|(19|20)[0-9]{2}-(0[1359]|11)-(0[1-9]|[12][0-9]|3[01])|(19|20)[0-9]{2}-02-(0[1-9]|1[0-9]|2[0-8])))T([01][0-9]|2[0-3]):([012345][0-9]):([012345][0-9]).[0-9]{3}Z)
Just to be clear - I didn't change much - Okipa did all the hard work and his regex validated the following value:
2021-10-04 14:38:03
I just altered it to include validation of the literal 'T' along with the fractional seconds and the UTC timezone indicator
2021-10-04T14:38:03.475Z
Cheers,
Rich
in my regex I've hardcoded the timezone offset. if you need it to reflect changing from UTC/GMT timezone to another timezone (e.g BST for British Summer Time or wherever you are in the world) then you'd need to change the regex so that it supports either plus/minus hours offset and the removal of the Z (zero) indicator.
cheers
Rich
Related Content
- 4 years ago
- 10 years ago
Recent Discussions
- 15 years ago