Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Beginner
Jan 28, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Validate Dates With Java

We can use java.text.DateFormat to validate dates. DateFormat is an abstract class for date/time formatting subclasses. It provides parsing methods for conversion of text into date. If the conversion cannot be carried out because of invalidity of the date, a java.text.ParseException is thrown. This is how we can know if a date was valid or not.

Say, we want to see if 2/29/2000 is a valid US date or not. In other words, we want to check if year 2000 is a leap year or not, and we want to use the US format for dates (MM/DD/YYYY).

We can write:

String dateStr = "2/29/2000"; 
DateFormat d = 
      DateFormat.getDateInstance(DateFormat.SHORT, Locale.US); 
Note that we have used the SHORT style to obtain the date/time fomatter, as a result we get "M/d/yy" for US locale:
We have to set the leniency of the parser to false, otherwise with an invalid date, the parser may use heuristics to interpret inputs that do not precisely match DateFormat object's format. With stricter parsing (leniency set to false), inputs must match this DateFormat object's format. Try:
   System.out.println(dateStr+" is a valid"); 
catch(java.text.ParseException pe) 
If we get here, the date supplied to the parser of DateFormat was not valid.
   System.out.println(dateStr+" is not valid"); 
Behrouz Fallahi
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date