java 将对象转换为日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30007520/
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
convert object into date
提问by Nono London
I get an ArrayList
of Object[]
from a database and I want to convert the java.sql.Date
stored in an object into a java.util.Date
(in order to use it in jfreechart):
my code is as follows:
我从数据库中得到一个ArrayList
of Object[]
,我想将java.sql.Date
存储在一个对象中的对象转换为一个java.util.Date
(以便在 jfreechart 中使用它):我的代码如下:
fills up the Array of object with data from MySQL
用来自 MySQL 的数据填充对象数组
ArrayList<Object[]> mydata=new ArrayList<>();
mydata=sqlGetter.getMdbObjectList(sqlString, null);
for(Object[] myobject : mydata){
if (myobject[1].getClass()==java.sql.Date.class){
java.util.Date mydate=null;
mydate = Date ( myobject[1]);
}
}
Netbeans return an error: "Java incompatible types: Object cannot be converted to Date"
Netbeans 返回错误:“Java 不兼容类型:对象无法转换为日期”
While I understand the idea, I would have expected to be able to cast the object into a Date after having checked that it is indeed of the right class.
虽然我理解这个想法,但在检查它确实是正确的类之后,我希望能够将对象转换为 Date。
I'm starting java, so please any helps on the obvious mistake that I must be doing would be useful.
我正在开始使用 Java,因此请对我必须做的明显错误提供帮助。
回答by Mureinik
You are missing a cast. Additionally, you'd be better off using the instanceof
operator:
你缺少演员。此外,您最好使用instanceof
运算符:
for(Object[] myobject : mydata){
// Note that java.sql.Date extends java.util.Date
if (myobject[1] instanceof java.util.Date) {
java.util.Date mydate = (java.util.Date) myobject[1];
}
}
回答by Luthoz
you just need to explicit cast the object to Date ex: (Date) obj;
您只需要将对象显式转换为 Date ex: (Date) obj;