1

Possible Duplicate:
How to sanity check a date in java

I want to convert a String into Date..with a condition that accepted String format should be only this yyyy/MM/dd-HH:MM:SS.

Date provided in any other format should give error.

try {
    String str_date = "25/09/2012-13:43:20";
    DateFormat formatter;
    Date date;
    formatter = new SimpleDateFormat("yyyy/MM/dd-hh:mm:ss");
    date = (Date) formatter.parse(str_date);
    System.out.println("Today is " + date);
} catch (ParseException e) {
    System.out.println("Exception :" + e);
}

Since str_date is having format dd/MM/yyyy-hh:mm:ss, which is invalid it should through exception, but it is not throwing any expection.

The output is Today is Mon Mar 05 13:43:20 IST 31

Community
  • 1
  • 1
Beginner
  • 855
  • 9
  • 21
  • 37

4 Answers4

7

I just a quick look at the Java doc for the parse method you are using and it says this:

By default, parsing is lenient: If the input is not in the form used by this object's format method but can still be parsed as a date, then the parse succeeds. Clients may insist on strict adherence to the format by calling setLenient(false).

Try putting formatter.setLenient(false); on the line after formatter is instantiated. That will force the formatter to use ONLY the format you have specified.

Maybe_Factor
  • 370
  • 3
  • 10
  • I tried it in the above way, but then also it is given exception even for the correct format. – Beginner Sep 26 '12 at 07:03
  • try { String str_date="2012/09/25-13:42:05"; SimpleDateFormat formatter ; Date date ; formatter = new SimpleDateFormat("yyyy/MM/dd-hh:mm:ss"); formatter.setLenient(false); date = (Date)formatter.parse(str_date); System.out.println("Today is " +date ); } catch (ParseException e) {System.out.println("Exception :"+e); } } – Beginner Sep 26 '12 at 07:05
2
  formatter.setLenient(false);

shall provide you with desired exception

Froum javadocs:

By default, parsing is lenient: If the input is not in the form used by this object's format method but can still be parsed as a date, then the parse succeeds. Clients may insist on strict adherence to the format by calling setLenient(false).

Konstantin Pribluda
  • 12,329
  • 1
  • 30
  • 35
0

From the Javadoc:

ParseException - if the *beginning* of the specified string cannot be parsed.

Try

String str_date="25:09/2012-13:43:20";

This will throw a ParseException.

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
0

Your format should specify HH rather than hh. Otherwise, 13 o'clock is time to get a new watch.

phatfingers
  • 9,770
  • 3
  • 30
  • 44