通过向上转换将 Java.sql.date 转换为 Java.util.date 安全吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2165025/
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-29 19:47:15  来源:igfitidea点击:

Safe to convert Java.sql.date to Java.util.date by up casting?

javadatejdbc

提问by Daniel Bingham

Java.sql.date extends java.util.date, so is it save to convert between the two by casting a java.sql.date as a java.util.date? Or is there some other way to convert them?

Java.sql.date 扩展了 java.util.date,那么通过将 java.sql.date 转换为 java.util.date 是否可以在两者之间进行转换?或者有其他方法可以转换它们吗?

回答by mattjames

You don't necessarily need to cast, you can just treat a SQL Date as if it was a util Date:

您不一定需要强制转换,您可以将 SQL 日期视为 util 日期:

java.sql.Date sqlDate = new java.sql.Date(whenever);
java.util.Date utilDate = sqlDate;

Compiles and runs just fine.

编译并运行得很好。

回答by BalusC

Yes, you can just upcast it.

是的,你可以向上投射它。

The java.sql.Dateis in fact nothing less or more than a representation of the SQL Date type, which has only year, month and day filled.

java.sql.Date其实无外乎或超过了SQL日期类型,它只有年月日填写的表示。

回答by itsraghz

Though you can easily obtain the java.sql.Date from java.util.Date, you need to be careful that java.sql.Date has only Date information minus time details.

虽然您可以轻松地从 java.util.Date 获取 java.sql.Date,但您需要注意 java.sql.Date 只有日期信息减去时间详细信息。

If needed, you need to look at java.sql.Time or java.sql.Timestamp.

如果需要,您需要查看 java.sql.Time 或 java.sql.Timestamp。