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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15207158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:51:19  来源:igfitidea点击:

Java: java.util.date cannot be cast to java.sql.Time

javasqltimeinsert

提问by Martin Nemeth

I have time converted from millis and now i would like to make an SQL Insert with that time value. I tried this but it is not working:

我有从毫秒转换的时间,现在我想用那个时间值做一个 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();

Any suggestions please?

请问有什么建议吗?

回答by BloodShura

java.sql.Timeextends java.util.Date, so you cannot simply cast it.

java.sql.Timeextends java.util.Date,所以你不能简单地投射它。

You can try something like this:

你可以尝试这样的事情:

Time time = new Time(date.getTime());

回答by Susie

The following is what I did when I had a similar problem.

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

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

Substitute a real date for "mm/dd/yyyy"

用真实日期代替“mm/dd/yyyy”

回答by Hari Menon

calendar1.getTime()returns a Dateobject, and Timeis a sub-class of Date, so a Datecannot be cast into a Time. You can try this instead:

calendar1.getTime()返回一个Date对象,并且Time是 的子类Date,因此 aDate不能转换为 a Time。你可以试试这个:

Time Cas2 = new Time(calendar1.getTimeInMillis());

回答by hthserhs

public class Time extends java.util.Date

It is not possible to cast Dateto Time.

无法投射DateTime.

You can use this instead:

您可以改用它:

Time time = new Time(date.getTime())

回答by Gilbert Le Blanc

You can try this. I've not tested the code.

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

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

You might have to subtract the zone offset.

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