Why dont you just try to parse the date? If it throws an exception on parsing then you know its invalid... or even better, make the user enter the date with a date time picker in case its coming from an UI.
Time is what we want the most, but what we use the worst. -- William Penn
Chinna Eranna wrote:I dont think SimpleDateFormat will here. Because SimpleDateFormat will parse this string successfully (after removing spaces), and gives a date of March 2nd or 3rd.
SimpleDateFormat extends java.text.DateFormat which has a method setLenient( boolean) which by default is 'true'. Set to 'false' and then it will throw the exception.
I'm a great fan of regex but this is not the right place to use it. Especially since the OP's regex allows '-' as a field separator but the SimpleDateFormat pattern does not! I would not even use a regex to convet the '-' separators to '/'; I would just use String.replace() .
My suggestion is to split the string and validate using a simple algorithm. Having a complex regex will make code unreadable.
If one has to check the syntax before parsing then I would use a regex and I would comment the regex so that it is not unreadable.
Retired horse trader.
Note: double-underline links may be advertisements automatically added by this site and are probably not endorsed by me.
Not everyone is aware of the fact that you can parse dates with DateFormat (and numbers with NumberFormat) without getting exceptions, using the "other" parse method:
This is similar to how parse(String) is implemented:
pos.index (pos.getIndex() from other packages) returning 0, the result Date being null or pos.getErrorIndex() returning a value other than -1 all indicate error.
I still don't like one thing about this solution: if the String has a valid date followed by some other garbage (e.g. "02/31/2100abc") the date will be parsed successfully, and success is shown. I usually make it a bit more strict:
If the ParsePosition's index is not equal to the String length there is some garbage after the valid date; only if these two are equal is the entire String used for the valid Date.