Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

java - How to solve this error "String Cannot be converted to Date"?

Hello I am trying to store the birthdate of the user in database with the code below:

 private void btnActionPerformed(java.awt.event.ActionEvent evt) {                                                 

    String username = txtUserName.getText();
    String password = txtPassword.getText();
    String email = txtEmail.getText();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String birthdate = sdf.format(JDateChooser.getDate());      
    Users user = new Users();
    user.setUserName(cin);
    user.setPassWord(firstName);
    user.setEmail(email);
    user.setBirthDate(birthdate);
    try {        
       int count = Users.getInstance().insert(user);
       if(count == 1){
       JOptionPane.showMessageDialog(null,"success");
       reset();
       }else{
       JOptionPane.showMessageDialog(null,"Faild");
       }
    } catch (Exception ex) {
        Logger.getLogger(AddNewPatient.class.getName()).log(Level.SEVERE, null, ex);
    }
} 

I got an error which says String connot be converted to Date in the line "user.setBirthDate(birthdate);" Because the parameter birthdate is assigned as Date type in the encapsulation(setBirthDate) is there any way to solve this issue, I am new in java programming and I am trying to improve my skills in java.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If this returns a Date:

JDateChooser.getDate()

And what you need is a Date, then don't convert it to a String. Just keep it as a Date:

Date birthdate = JDateChooser.getDate();
// later...
user.setBirthDate(birthdate);

Note that you can then also remove this line, since you're not using the variable it declares:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

In general you want to keep data types in their raw form pretty much as often as possible. Unless there's a specific need for something to be represented as a string (displaying it to the user, sending it over a serialized API of some kind, etc.) then just use the data as-is instead of converting it to something else.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...