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

3

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?

Aerophyte answered 1/6, 2015 at 13:19 Comment(3)
possible duplicate of How to sanity check a date in javaPitchfork
@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.Aerophyte
Where possible avoid the java Date classes. Use joda.org/joda-time for Java 7 and older, and Java Time in Java 8.Magnetograph
E
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
}
Eligible answered 1/6, 2015 at 13:24 Comment(6)
Should that be setLenient(false) to be strictAssailant
@TimoSta: No, this didn't solved the problem. I am still getting the same answer.Aerophyte
@BrettWalker Correct, it should be falseEligible
@ShirgillAnsari Have a look at my edit. It should be set to false instead of true as Brett Walker pointed out.Eligible
@TimoSta: Did you try with String dateStr = "Mon Jan 30 00:00:00 IST 2015"; In this case, it must not fail, but an unparseable exception is thrown.Aerophyte
@TimoSta: It's fine TimoSta. Jan 30 is not Monday. How can I be so stupid this evening?Aerophyte
I
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);
Inquiring answered 1/6, 2015 at 13:25 Comment(0)
Z
1

Set the date formatter not to be lenient...

DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
formatter.setLenient(false);
Zeller answered 1/6, 2015 at 13:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.