I'm just wondering if there is a way (maybe with regex) to validate that an input on a Java desktop app is exactly an string formated as: "YYYY-MM-DD".
I've searched but with no success.
Thank you
I'm just wondering if there is a way (maybe with regex) to validate that an input on a Java desktop app is exactly an string formated as: "YYYY-MM-DD".
I've searched but with no success.
Thank you
The following regex will accept YYYY-MM-DD (within the range 1600-2999 year) formatted dates taking into consideration leap years:
Examples:
You can test it here.
Note: if you want to accept one digit as month or day you can use:
I have created the above regex starting from this solution
If you want a simple regex then it won't be accurate. https://www.freeformatter.com/java-regex-tester.html#ad-output offers a tool to test your Java regex. Also, at the bottom you can find some suggested regexes for validating a date.
ISO date format (yyyy-mm-dd):
ISO date format (yyyy-mm-dd) with separators '-' or '/' or '.' or ' '. Forces usage of same separator accross date.
United States date format (mm/dd/yyyy)
Hours and minutes, 24 hours format (HH:MM):
Good luck
Putting it all together:
REGEX
doesn't validate values (like "2010-19-19")SimpleDateFormat
does not check format ("2010-1-2", "1-0002-003" are accepted)it's necessary to use both to validate format and value:
A ThreadLocal can be used to avoid the creation of a new SimpleDateFormat for each call.
It is needed in a multithread context since the SimpleDateFormat is not thread safe:
(same can be done for a Matcher, that also is not thread safe)
You need more than a
regex
, for example "9999-99-00" isn't a valid date. There's aSimpleDateFormat
class that's built to do this. More heavyweight, but more comprehensive.e.g.
Unfortunately,
SimpleDateFormat
is both heavyweight and not thread-safe.For fine control, consider an InputVerifier using the
SimpleDateFormat("YYYY-MM-dd")
suggested by Steve B.