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
  • 16,318
  • 31
  • 86
  • 141
Farhan stands with Palestine
  • 13,890
  • 13
  • 58
  • 105
  • 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 stands with Palestine 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
  • 41,396
  • 16
  • 88
  • 94
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
  • 198,278
  • 20
  • 158
  • 249
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,146
  • 13
  • 24