Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent invalid date from getting converted into date of next month in jdk6?

Tags:

java

jdk6

Consider the snippet:

String dateStr = "Mon Jan 32 00:00:00 IST 2015";    // 32 Jan 2015

DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
DateFormat ddMMyyyy = new SimpleDateFormat("dd.MM.yyyy");
System.out.println(ddMMyyyy.format(formatter.parse(dateStr)));

gives me the output as

01.02.2015     //   Ist February 2015

I wish to prevent this to make the user aware on the UI that is an invalid date?
Any suggestions?

like image 928
Farhan Shirgill Ansari Avatar asked Jun 01 '15 13:06

Farhan Shirgill Ansari


2 Answers

The option setLenient() of your SimpleDateFormat is what you are looking for.

After you set isLenient to false, it will only accept correctly formatted dates anymore, and throw a ParseException in other cases.

String dateStr = "Mon Jan 32 00:00:00 IST 2015";    // 32 Jan 2015

DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
formatter.setLenient(false);
DateFormat ddMMyyyy = new SimpleDateFormat("dd.MM.yyyy");
try {
    System.out.println(ddMMyyyy.format(formatter.parse(dateStr)));
} catch (ParseException e) {
    // Your date is invalid
}
like image 157
TimoStaudinger Avatar answered Sep 22 '22 10:09

TimoStaudinger


You can use DateFormat.setLenient(boolean) to (from the Javadoc) with strict parsing, inputs must match this object's format.

DateFormat ddMMyyyy = new SimpleDateFormat("dd.MM.yyyy");
ddMMyyyy.setLenient(false);
like image 28
Elliott Frisch Avatar answered Sep 22 '22 10:09

Elliott Frisch