Some times, when you are parsing a date string against a pattern(such as MM/dd/yyyy) using java.text.SimpleDateFormat, strange things might happen(for unknown developers) if your date string is a dynamic content entered by user in some input field on the user interface and if it is not entered in the specified format.
The parse method, in the SimpleDateFormat parses the date string, which is in incorrect format and returns you date object, instead of throwing a java.text.ParseException. However, the date returned is not what is expected by you.
The below code-snippet shows you this behaviour.
package com.starwood.system.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateSample {
public static void main(String args[]){
SimpleDateFormat sdf = new SimpleDateFormat () ;
sdf.applyPattern("MM/dd/yyyy") ;
try {
Date d = sdf.parse("2011/02/06") ;
System.out.println(d) ;
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Output: Thu Jul 02 00:00:00 MST 173
See the output, that is a date back in the year 173.
To avoid this problem, call the setLenient (false) on SimpleDateFormat instance. That will make the parse method to throw ParseException when the given input string is not in the specified format.
Here is the modified code-snippet.
package com.starwood.system.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateSample {
public static void main(String args[]){
SimpleDateFormat sdf = new SimpleDateFormat () ;
sdf.applyPattern("MM/dd/yyyy") ;
sdf.setLenient(false) ;
try {
Date d = sdf.parse("2011/02/06") ;
System.out.println(d) ;
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Output:
java.text.ParseException: Unparseable date: "2011/02/06"
at java.text.DateFormat.parse(Unknown Source)
at com.starwood.system.util.DateSample.main(DateSample.java:14)
Thanks for this share!
Thanks for the explanation.
Thanks for the explanation.