7

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?

BuZz
  • 14,398
  • 28
  • 80
  • 133
Farhan Shirgill Ansari
  • 13,530
  • 10
  • 51
  • 100
  • 1
    possible duplicate of [How to sanity check a date in java](http://stackoverflow.com/questions/226910/how-to-sanity-check-a-date-in-java) – Jens Jun 01 '15 at 13:22
  • @Jens: The main problem is that how will I get dd.MM.yyyy format with Calendar class and then do the stuff with setLenient method. – Farhan Shirgill Ansari Jun 01 '15 at 13:23
  • 1
    Where possible avoid the java `Date` classes. Use http://www.joda.org/joda-time/ for Java 7 and older, and Java Time in Java 8. – Thirler Jun 01 '15 at 13:23

3 Answers3

3

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
}
TimoStaudinger
  • 38,697
  • 15
  • 86
  • 91
2

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);
Elliott Frisch
  • 191,680
  • 20
  • 149
  • 239
1

Set the date formatter not to be lenient...

DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
formatter.setLenient(false);
Phil Anderson
  • 3,116
  • 12
  • 24