-1

I want to convert a string to time using the parse method which is going to be inserted to database later. But I get: Incompatible Types: Java.util.date cannot be converted to Java.sql.Date. Any Solution?

String s = time.getText();
    DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
    Date d = sdf.parse(s);
Rym Haouachi
  • 21
  • 1
  • 6
  • Do you need a `java.sql.Time`? For your database? Which database? If you can use Java 8, you will probably want to check if your database can use a `java.time.LocalTime` instead, or one of the other classes in `java.time`. They are generally nicer to work with than the old classes from Java 1.0 and 1.1. – Ole V.V. Apr 09 '17 at 18:21
  • Yes I think I do. I'm using Mysql database and I can't get rid of the java.sql.Time because it doesn't accept any other type of object than time – Rym Haouachi Apr 09 '17 at 18:46
  • I’m far away from my home field here, but the way I read https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-versions.html, Connector/J version 5.1 supports JDBC version 4.2, which if my memory serves me right, should be enough that it can use the `java.time` classes. If this is correct, you can do without `java.sql.Time`. Haven’t been able to find it the docs, though. – Ole V.V. Apr 09 '17 at 19:00
  • Will try that but it's gonna make me change a lot of things in my project. Thank you – Rym Haouachi Apr 09 '17 at 20:29

2 Answers2

0

SimpleDateFormat parse() method returns java.util.Date whereas you have imported java.sql.Date, so change the imported class to java.util.Date

Vasu
  • 21,832
  • 11
  • 51
  • 67
0

the errors occurs when java.sql.Date imported which is derived from java.util.Date, and DateFormat.parse return a java.util.Date. so you can't assign java.util.Date to derived type java.sql.Date.

import java.util.Date;
//not 
import java.sql.Date;

OR assign it to a full-name type of java.util.Date when you both using java.sql.Date and java.util.Date:

java.util.Date d = sdf.parse(s);

OR if you need convert java.util.Date to a java.sql.Date you can do as follows:

java.sql.Date d = new java.sql.Date(sdf.parse(s).getTime());

OR if you need convert java.util.Date to a java.sql.Time you can do as follows:

java.sql.Time d = new java.sql.Time(sdf.parse(s).getTime());
holi-java
  • 29,655
  • 7
  • 72
  • 83