I'm using
java.util.Date date;
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
try {
date = sdf.parse(inputString);
} catch (ParseException e) {
e.printStackTrace();
}
where inputString
is a string in the dd/MM/yyyy
format.
If the inputString
is, for example, 40/02/2013, I would to obtain an error, instead the parse method returns the Date 12 March 2013 (12/03/2013).
What I'm wronging?
Set the Leniency bit:
public void setLenient(boolean lenient)
Specify whether or not date/time parsing is to be lenient. With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object's format. With strict parsing, inputs must match this object's format.
The following code:
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class Tester {
public static void main(String[] argv) {
java.util.Date date;
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
// Lenient
try {
date = sdf.parse("40/02/2013");
System.out.println("Lenient date is : "+date);
} catch (ParseException e) {
e.printStackTrace();
}
// Rigorous
sdf.setLenient(false);
try {
date = sdf.parse("40/02/2013");
System.out.println("Rigorous date (won't be printed!): "+date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Gives:
Lenient date is : Tue Mar 12 00:00:00 IST 2013
java.text.ParseException: Unparseable date: "40/02/2013"
at java.text.DateFormat.parse(DateFormat.java:357)
Notes
- When in doubt about a Java class, reading the class documentation should be your first step. I didn't know the answer to your question, I just Googled the class, clicked on the parse method link and noted the See Also part. You should always search first, and mention your findings in the question
- Lenient dates have a respectable history of bypassing censorship and inspire children's' imagination.