1

I am trying to insert Date into Database but I am getting error as java.util.Date cannot be cast to java.sql.Date. Please help.

String next_dt = req.getParameter("NextDate");
DateFormat dtFmt = null;
dtFmt = new SimpleDateFormat("yyyy-MM-dd");
dtToday = (Date) dtFmt.parse(next_dt);
Kimaya
  • 35
  • 2
  • 2
  • 6
  • That's cause `java.util.Date` isn't a child of `java.sql.Date`, it's the other way round. I believe you can use `new java.sql.Date(dtToday.getTime());` – MadProgrammer Feb 04 '15 at 06:50
  • `sqlDate = new Date(javaDate.getTime());` I think dtToday is the date you want to insert. you need to convert it to sql date – shikjohari Feb 04 '15 at 07:00

5 Answers5

4

You have imported java.sql.Data. But dtFmt.parse(next_dt); returns an object of type java.util.Date so you have to change

import java.sql.Date;

to

import java.util.Date;
Jens
  • 67,715
  • 15
  • 98
  • 113
  • I tried that too but then i am not able to insert dtToday into table. – Kimaya Feb 04 '15 at 06:59
  • If you need the date for sql statements, you have to convert the `java.Util.Date`to an `java.sql.Date` See [here](http://stackoverflow.com/questions/530012/how-to-convert-java-util-date-to-java-sql-date) how you can do it. – Jens Feb 04 '15 at 07:02
2

Add following lines - as it needs to be a sql Date and not util date

java.sql.Date sqlDate = new java.sql.Date(dtToday.getTime());
//now insert this sqlDate
shikjohari
  • 2,278
  • 11
  • 23
1

DateFormat.parse() returns a java.util.Date, and you're trying to illegally cast it to a java.sql.Date.

Assuming you continue to import java.sql.Date, you can successfully assign the variable like so:

dtToday = new Date(dtFmt.parse(next_dt).getTime());
gknicker
  • 5,509
  • 2
  • 25
  • 41
1

You should use java.sql.Timestamp or java.sql.Date instead of java.util.Date Problem with java.sql.Date is that it will not store time. So using Timestamp is the approach i always take. As it is the child class of java.util.date it is compatible with both date and timestamp columns in DB.

Lokesh
  • 7,810
  • 6
  • 48
  • 78
0
public static java.sql.Date convertFromJAVADateToSQLDate(
        java.util.Date javaDate) {
    java.sql.Date sqlDate = null;
    if (javaDate != null) {
        sqlDate = new Date(javaDate.getTime());
    }
    return sqlDate;
}

As the name of the class is same use should give fully qualified name(FQN) of both classes you also can use format method to convert date to proper SQL format date.

public static String toMysqlDateStr(Date date) {
String dateForMySql = "";
if (date == null) {
    dateForMySql = null;
} else {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    dateForMySql = sdf.format(date);
}

return dateForMySql;

}

Pert8S
  • 582
  • 3
  • 6
  • 21