Java:Java.util.date不能强制转换为Java.sql.Time

Java:Java.util.date不能强制转换为Java.sql.Time,java,sql,time,insert,Java,Sql,Time,Insert,我已经从毫秒转换了时间,现在我想用这个时间值进行SQL插入。我尝试过这个,但不起作用: String INSERT_RECORD ="INSERT INTO PRAVIDLA (CAS,DEN,MIESTNOST,STAV) values(?,?,?,?)"; PreparedStatement pstmt = con.prepareStatement(INSERT_RECORD); Calendar calendar1 = Calendar.g

我已经从毫秒转换了时间,现在我想用这个时间值进行SQL插入。我尝试过这个,但不起作用:

        String INSERT_RECORD ="INSERT INTO PRAVIDLA (CAS,DEN,MIESTNOST,STAV) values(?,?,?,?)";
        PreparedStatement pstmt = con.prepareStatement(INSERT_RECORD);

        Calendar calendar1 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));       
        calendar1.setTimeInMillis(milli);
        Time Cas2 = (Time) calendar1.getTime();

        pstmt.setTime(1, Cas2);
        pstmt.setInt(2, DEN);
        pstmt.setString(3, MIESTNOST);
        pstmt.setString(4, STAV);
        pstmt.executeUpdate();
有什么建议吗?

calendar1.getTime()
返回一个
Date
对象,
Time
Date
的子类,因此
日期
不能转换为
时间。您可以尝试以下方法:

Time Cas2 = new Time(calendar1.getTimeInMillis());
Time time = new Time(date.getTime())

java.sql.Time
扩展了
java.util.Date
,因此不能简单地强制转换它

您可以尝试以下方法:

Time time = new Time(date.getTime());
无法将日期转换为时间

您可以改为使用此选项:

Time Cas2 = new Time(calendar1.getTimeInMillis());
Time time = new Time(date.getTime())

你可以试试这个。我还没有测试代码

Time time = new Time(calendar.get(Calendar.MILLISECOND) 
            + calendar.get(Calendar.ZONE_OFFSET));

您可能需要减去分区偏移量。

以下是我遇到类似问题时所做的操作

java.util.Date utilDate = new java.util.Date("mm/dd/yyyy");
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

将“mm/dd/yyyy”替换为实际日期

您不能这样强制转换不同的类型。使用
Date
字段创建新的
Time
@SotiriosDelimanolis您以前使用过
java.sql.Time
吗?因为没有
java.util.Date
参数传递给它的构造函数。@luigimendoza的Dup不能使用
Time(long-Time)
的构造函数
Date\getTime()
?@luigimendoza已修复,现在使用另一个构造函数。