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"); } 
Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

kubernetes logging

Kubernetes Logging: What You Need to Know

Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes