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.....

Ambrish
  • 3,627
  • 2
  • 27
  • 42
sky3287944
  • 39
  • 1
  • 1
  • 12
  • 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. – hiergiltdiestfu Jun 05 '14 at 07:11
  • 1
    Check this [link](http://stackoverflow.com/questions/530012/how-to-convert-java-util-date-to-java-sql-date). – Ambrish Jun 05 '14 at 07:15

2 Answers2

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);
}
Fortega
  • 19,463
  • 14
  • 75
  • 113
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 ()

Fortega
  • 19,463
  • 14
  • 75
  • 113
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64