Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex date format validation on Java

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".

like image 459
Sheldon Avatar asked Jan 27 '10 19:01

Sheldon


2 Answers

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.

like image 106
Greg Bacon Avatar answered Sep 23 '22 11:09

Greg Bacon


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.

like image 39
Steve B. Avatar answered Sep 22 '22 11:09

Steve B.