devxlogo

Validate Dates With Java

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:

  d.setLenient(false);

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:

 {    d.parse(dateStr);    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"); } 
See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist