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);
2
  • 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()); Commented Feb 4, 2015 at 6:50
  • sqlDate = new Date(javaDate.getTime()); I think dtToday is the date you want to insert. you need to convert it to sql date Commented Feb 4, 2015 at 7:00

5 Answers 5

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;
Sign up to request clarification or add additional context in comments.

2 Comments

I tried that too but then i am not able to insert dtToday into table.
If you need the date for sql statements, you have to convert the java.Util.Dateto an java.sql.Date See here how you can do it.
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

Comments

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());

1 Comment

Still not able to insert in database..
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.

Comments

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;

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.