简体   繁体   中英

How to check whether a Birth Date entered is valid

A user enters his birth date in a jTextfield in the yyyy/mm/dd and I want to make sure that he enters it correctly like that and also that it is a real date. this is my code so far:

SimpleDateFormat df = new SimpleDateFormat("yyyy/mm/dd");  
Date testDate = null;

Birth = jTextField3.getText();

try{  
    testDate = df.parse(Birth);
} catch (ParseException e){ }      
if (!df.format(testDate).equals(Birth)){  
    JOptionPane.showMessageDialog(rootPane, "invalid date!!");
}

the error I am getting is it said I cant cast a java.sql.Date into a java.util.Date

mm is minutes. MM is months:

SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

See the documentation for more details.

You should set that to be strict ( df.setLenient(false) , and then you don't need to try to format the result again - just the parse exception should be enough.

Personally I'd use Joda Time for any date/time work in Java though - it's a much nicer API.

As for java.util.Date vs java.sql.Date - the code you've given us would entirely use java.util.Date . If you've already got an import for java.sql.Date which you want to preserve, you'd want something like:

java.util.Date testDate = ...;

Although as you don't need to reformat it, you may not even need a variable at all:

SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
df.setLenient(false);
Date testDate = null;
boolean valid = false;
try {
    df.parse(jTextField3.getText());
    valid = true;
}
catch (ParseException e) { } // valid will still be false
if (!valid) {  
    JOptionPane.showMessageDialog(rootPane, "invalid date!!");
}

(Or you could show the message dialog in the catch block, but then you can't easily have an else clause for the success case...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM