tags:

views:

57

answers:

2

Hello,

I have this code for checking whether the Date is OK or not, but it's not ckecking all the cases. For example when text="03/13/2009" as this date doesn't exist in the format "dd/MM/yyyy" it parses the date as 03/01/2010. Is there any way to change this behaviour and getting an exception when I try to parse a Date which is not correct? What's the best way to do this validation?

public static final String DATE_PATTERN = "dd/MM/yyyy";

public static boolean isDate(String text){
     SimpleDateFormat formatter = new SimpleDateFormat(DATE_PATTERN);
     ParsePosition position = new ParsePosition(0);
     formatter.parse(text, position);
     if(position.getIndex() != text.length()){
         return false;
     }else{
        return true;
     }
}

Thanks.

A: 

In my opinion the best way to validate date is to use regular expression, you can find here many of them also for validating dates http://regexlib.com/DisplayPatterns.aspx Java has good support for regular expressions, some tutorial here http://java.sun.com/docs/books/tutorial/essential/regex/index.html

sanjuro
No, you should go with a better date parsing library. Date parsing is too complex to try to do it yourself. Hopefully someone else knows a good one...
Thilo
i don't understand you, why are you making things harder? Regular expressions are good way to parse dates and you can configure your own pattern. If you are not making multiinternational space super website or app, it is good and reliable option to do that. and i wrote in my opinion!
sanjuro
I agree Thilo, it's quite difficult to do it with regular expressions. For example the 29th february exists only every 4 years, these things makes it too complex to be handled easily in a regular expression.
Javi
yes it is little complex, but many complete regexps are on that site i provided and you don't need to write your own, or you can alter the existing regexp.
sanjuro
+7  A: 

You need to set lenient to false before parsing, otherwise the parser will "guess" and try to correct invalid dates

formatter.setLenient(false);

Check out http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html#setLenient(boolean)

Kennet