I need to find a regex that will match both date formats:
MM/dd/yyyy and M/d/yyyy
ex. 01/31/2022, 1/1/2022, 12/13/2022, 12/1/2022
So far I tried
^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9]{1}$)/[0-9]{4}$
Which seems to be the closes to what I need, but it's still not perfect. I am on Java 7 and I need to validate user's input, thus I need to verify if they gave me correct date format. For example, if they enter 13/1/2022, then SimpleDateFormat translates this to Sun Jan 01 00:00:00 CET 2023.
For Java 8+, I recommend this answer by Alexander Ivanchenko. With Java 6 or 7, you can still use that answer with the help of ThreeTen Backport library which backports
java.timeAPI to Java 6 and 7.However, if you do not want to use the ThreeTen-Backport library and want to stick to Java standard library, you can use
DateFormat#setLenient(boolean)withfalseas the value.Demo:
Output: