Monday, October 17, 2011

Date Validation in Java

Java's DataFormat class may be very familiar to you. We use it very often when we want to format a Date object, for example;


public class DateValidationExample {
   
    public static void main(String[] args) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy");

        String formattedDate = simpleDateFormat.format(new Date()); 

        System.out.println(formattedDate); 

     }
}
The output will be  

      "01-Nov-2011"

Now let's try it the other way around. Let's try to parse a String as a Date.


public class DateValidationExample {
   
    public static void main(String[] args) {

        String dateAsString = "01-Nov-2011";

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy"); 

        Date date = simpleDateFormat.parse(dateAsString); 

        System.out.println(date); 

     }
}

The output will be

      "Tue Nov 01 00:00:00 GMT 2011"

Now let's try "31-Nov-2011". Note that November doesn't have a 31st. But if we try the following code it will give an output without any problem.


public class DateValidationExample {
   
    public static void main(String[] args) {

        String dateAsString = "31-Nov-2011";

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy"); 

        Date date = simpleDateFormat.parse(dateAsString); 
        
        System.out.println(date); 

     }
}


The output will be 

      "Thu Dec 01 00:00:00 GMT 2011" 

How does this happen ?

Although the month November has only 30 days, the parser will assume that the user means,

      "30th November + 1 day"

So it will give the output as 1st of December.

But in some cases we need to validate the dates. For example, when we check for input validation, when a user enters an invalid date like the above 30th of November or 31st of February, our program should be capable of validating the date and showing user the date entered is incorrect. So how can this be achieved in Java ?

Answer is simple. In Java DateFormat class, there is a method called 'setLenient()'. When we set this setLenient(false) in our code it will check whether the date is a correct calendar date, otherwise throws an exception.

Let's try the following code to clearly understand this. 



public class DateValidationExample {
   
    public static void main(String[] args) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy"); 

        simpleDateFormat.setLenient(false);

        Date date = simpleDateFormat.parse("31-Nov-2011"); 

        System.out.println(date); 

     }
}

The output here is

      java.text.ParseException: Unparseable date: "31 Nov 2011"
 
Thus we can validate dates. :)

No comments: