Java:Java.util.date不能强制转换为Java.sql.Time
我已经从毫秒转换了时间,现在我想用这个时间值进行SQL插入。我尝试过这个,但不起作用: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
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已修复,现在使用另一个构造函数。