0

I am trying to convert a java date object to sql date object. I tried to implement something on my own and came up with the following:

try {
    rs.updateDate("", (java.sql.Date) new SimpleDateFormat("dd-MM-yyyy").parse(jTextFieldDate.getText()));
} catch (ParseException ex) {
    Logger.getLogger(helpdesk.class.getName()).log(Level.SEVERE, null, ex);
}

Here rs is a Result Set object and jTextFieldDate as the name suggests is a java text field object. Is this implementation correct. What are the possible problems i may encounter by using this code.....

2
  • Casting is not a conversion - it only works if the target type and the actual type are related in terms of class hierarchies and implemented interfaces, i.e. if the actual type already is the target type. You need a mapping, not a cast. Commented Jun 5, 2014 at 7:11
  • 1
    Check this link. Commented Jun 5, 2014 at 7:15

2 Answers 2

2

This will not work. You cannot cast a java.util.Date (returned by the parse method of SimpleDateFormat) to java.sql.Date. To convert the java.util.Date to java.sql.Date, you can do the following:

try {
    java.util.Date utilDate = new SimpleDateFormat("dd-MM-yyyy").parse(jTextFieldDate.getText());
    java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
    rs.updateDate("", sqlDate);
} catch (ParseException ex) {
    Logger.getLogger(helpdesk.class.getName()).log(Level.SEVERE, null, ex);
}
Sign up to request clarification or add additional context in comments.

Comments

2

The code

 new SimpleDateFormat("dd-MM-yyyy").parse(jTextFieldDate.getText()))

returns a java.util.Date not a java.sql.Date

You can construct a java.sql.Date using a long tm which you can from java.util.Date.getTime ()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.