setLenient Example in Java date

setLenient Example in Java date:

In any programming language, handling date will always be challenging at some scenario. In Java we are using SimpleDateFormat to validate the date.

If you see the below program it is behaving in a unexpected manner, which cause system/application instability,

package in.javadomain;

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class DateSetLenientExample {

public static void main(String[] args) {

try {
String inputDate = "29/11/2015";
SimpleDateFormat simpleDateFormat = newSimpleDateFormat("MM/dd/yyyy");
System.out.println(simpleDateFormat.parse(inputDate));
} catch (ParseException e) {
e.printStackTrace();
}

}

}

Output:

Thu May 11 00:00:00 IST 2017

Output is completely irrelevant to the input we have given. So it is always better and advisable to use setLenient(false); to avoid such improper behavior’s in date validations using SimpleDateFormat.

package in.javadomain;

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class DateSetLenientExample {

public static void main(String[] args) {

try {
String inputDate = "29/11/2015";
SimpleDateFormat simpleDateFormat = newSimpleDateFormat("MM/dd/yyyy");
simpleDateFormat.setLenient(false);
System.out.println(simpleDateFormat.parse(inputDate));
} catch (ParseException e) {
e.printStackTrace();
}

}

}

Output:

java.text.ParseException: Unparseable date: "29/11/2015"
at java.text.DateFormat.parse(Unknown Source)
at in.javadomain.DateSetLenientExample.main(DateSetLenientExample.java:14)

After we set simpleDateFormat.setLenient(false); parsing is validated with the format we are using in simpledateformat with the format of the input date given.

So we are getting atleast the parseException, rather than the improper behavior and invalid date’s as output.

It is always advisable to use the simpleDateFormat.setLenient(false); in date validations in java.

Note: simpleDateFormat.setLenient(true); will be same as the case 1, which prints the “Thu May 11 00:00:00 IST 2017”.

630 total views, 3 views today

Leave a Reply

Your email address will not be published. Required fields are marked *