I'm just wondering if there is a way (maybe with regex) to validate that an input on a Java desktop app is exactly a string formatted as: "YYYY-MM-DD".
Use the following regular expression:
^\d{4}-\d{2}-\d{2}$
as in
if (str.matches("\\d{4}-\\d{2}-\\d{2}")) { ... }
With the matches
method, the anchors ^
and $
(beginning and end of string, respectively) are present implicitly.
You need more than a regex
, for example "9999-99-00" isn't a valid date. There's a SimpleDateFormat
class that's built to do this. More heavyweight, but more comprehensive.
e.g.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); boolean isValidDate(string input) { try { format.parse(input); return true; } catch(ParseException e){ return false; } }
Unfortunately, SimpleDateFormat
is both heavyweight and not thread-safe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With