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:

 {    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"); } 
Share the Post:
Share on facebook
Share on twitter
Share on linkedin


The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS