Regex date validation for yyyy-mm-dd [duplicate]
what is the regex for the date format yyyy-mm-dd?
I want to validate the email from edittext and check if it matches the regex.
Solution 1:
This will match yyyy-mm-dd
and also yyyy-m-d
:
^\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])$
If you're looking for an exact match for yyyy-mm-dd
then try this
^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$
or use this one if you need to find a date inside a string like The date is 2017-11-30
\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])*
https://regex101.com/r/acvpss/1
Solution 2:
A simple one would be
\d{4}-\d{2}-\d{2}
Debuggex Demo
but this does not restrict month to 1-12 and days from 1 to 31.
There are more complex checks like in the other answers, by the way pretty clever ones. Nevertheless you have to check for a valid date, because there are no checks for if a month has 28, 30, or 31 days.
Solution 3:
You can use this regex to get the yyyy-MM-dd format:
((?:19|20)\\d\\d)-(0?[1-9]|1[012])-([12][0-9]|3[01]|0?[1-9])
You can find example for date validation: How to validate date with regular expression.