Leonardo
Leonardo

Reputation: 9857

Date format conversion not working as expected in Java

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

Answers (2)

Nishant Solanki
Nishant Solanki

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

Kris
Kris

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 :

  1. Have front end filtering (not allowing date strings that are shorter than 10 characters or otherwise ensure that the year is within a reasonable range.) Perhaps have JavaScript evaluate the date and if before 1900 (or whatever seems a good cutoff) display an error to the user (or autofix if that seems preferable, see 2 for issues with that)
  2. Evaluate the date object after parsing the date and 'fixing' any years that were clearly entered with only two characters (this can be tricky; how do you handle the cutoff from 19XX to 20XX?).
  3. Return an exception (presumably handled by the UI) for any dates falling before some cutoff (probably best used in conjunction with some client side validation)
  4. Only allow dates to be entered via web widgets (date pickers).

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

Related Questions