Tiny
Tiny

Reputation: 27899

Date with SimpleDateFormat in Java

The following code attempts to parse a date 31-Feb-2013 13:02:23 with a given format.

DateFormat dateFormat=new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
System.out.println(dateFormat.parse("31-Feb-2013 13:02:23"));

It returns Sun Mar 03 13:02:23 IST 2013.

I need to invalidate such dates indicating invalid date. This (and so forth) date shouldn't be parsed (or should be invalidated in any other way). Is this possible?

Upvotes: 3

Views: 1998

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213223

Use DateFormat.setLenient(boolean) method with false argument:

DateFormat dateFormat=new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
dateFormat.setLenient(false);
System.out.println(dateFormat.parse("31-Feb-2013 13:02:23"));

Upvotes: 4

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41200

Java Date calculation is lenient. With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object's format.

You must pass false to lenient to dateformat which truns to Strict mode. With strict parsing, inputs must match this object's format.

DateFormat dateFormat=new SimpleDateFormat("...");
dateFormat.setLenient(false); // turn on Strict mode
dateFormat.parse("31-Feb-2013 13:02:23");// throws java.text.ParseException 

Upvotes: 4

Related Questions