-1

I want to save date to oracle from eclipse java program. Right now I am using this code

    DateFormat dt=new SimpleDateFormat("MM/dd/yyyy");
    java.sql.Date dob=(java.sql.Date)dt.parse("02/02/2015");
    ob.setDateOfBirth(dob);

The table has a column named Date_of_birth having date datatype.

But i am getting an error

Exception in thread "main" java.lang.ClassCastException: 
java.util.Date cannot be cast to java.sql.Date
at com.TestCustomerDao.main(TestCustomerDao.java:22)

Please Help

Piyush Mittal
  • 1,860
  • 1
  • 21
  • 39
Vivek
  • 77
  • 3
  • 11
  • `dt.parse("02/02/2015");` this method will return `java.util.Date` object. you can use that one only.. – Prashant Aug 08 '15 at 18:38
  • Other duplicates and similar: [this](http://stackoverflow.com/q/18893863/642706), [this](http://stackoverflow.com/q/24652571/642706), [this](http://stackoverflow.com/q/28292468/642706), [this](http://stackoverflow.com/q/2942270/642706), and **most importantly**, [java.util.Date vs java.sql.Date](http://stackoverflow.com/q/2305973/642706). – Basil Bourque Aug 08 '15 at 19:54

1 Answers1

1

The class that DateFormat.parse(String) returns is java.util.Date.

You need a java.sql.Date, which is actually a subclass of the above. You can only cast an object up to a class it inherits from, you can't cast down to a class that inherits from it.

In order to do that properly, you need to create a new java.sql.Date object from the java.util.Date object by using:

java.sql.Date dob = new java.sql.Date( dt.parse("02/02/2015").getTime() );

This gets the internal time stamp (representation of time as milliseconds since January 1970) from the java.util.Date object, and creates a java.sql.Date that is based on the same time stamp.

RealSkeptic
  • 33,993
  • 7
  • 53
  • 79