Reputation: 9857
this is a well known question already appeared on stackoverflow.
I have been asked to solve a bug in a web application.
I have a date coming from a web form, the user is supposed to enter a valid date in a given format dd/MM/yyyy
.
The application is using Struts 1.3 as a framework, and this is what I found in validate method of the corresponding FormBean.
DateFormat dateFormat = new SimpleDateFormat( "dd/MM/yyyy", aLocale );
try{
mydate = dateFormat.parse( formDate );
}
catch( ParseException pe ){
errors.add( "error", new ActionError( "error.date.invalid" ) );
}
However it's happening that the error is not raised for example when user enter year in short format, i.e. 01/10/12
, which is converted into a date, looking in database I found 01/10/0012
.
As a quick fix I tried to use setLenient(false)
, but the exception is still not raised, and mydate still results in a valid but wrong date.
Before going to mess with regex and string pre parsing, I was wondering if I am missing something. Especially when locale is used within date format instantiation.
Current Jdk used in project is 1.5
Upvotes: 0
Views: 890
Reputation: 66
You can use format pattern like:
DateFormat dateFormat = new SimpleDateFormat( "dd/MM/yy", aLocale );
So it will convert "01/11/12" to Jan 11, 2012 and "01/11/86" to Jan 11, 1986
if Year is in "yyyy" format than the year is interpreted literally, regardless of the number of digits.
For more details read : http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html#year
Or you can handle User input in javascript/Java code for "dd/mm/yyyy" format. Resctrict user to enter date in "dd/mm/yyyy" format only.
Upvotes: 1
Reputation: 14458
The problem is that 01/10/12
does satisfy dd/MM/yyyy
. It's just that it (as you've discovered) refers to 12 AD.
Your options are :
My vote would be for a combination of 1 and 3. 1 for the case where JavaScript is enabled and 3 to handle the rare instances where JS validation fails.
Upvotes: 0