将字符串转换为日期 Java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5499613/
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
Cast string to date Java
提问by user195257
Any ideas why this isnt working?
任何想法为什么这不起作用?
DateFormat df = new SimpleDateFormat("dd/mm/yyyy");
Date date1 = null, date2 = null;
String start, finish;
System.out.println("Please enter a start date:");
while(date1 == null){
try{
start = scan.next();
date1 = (Date) df.parse(start);
}catch(ParseException e){
System.out.println("Please enter a valid date!");
}
}
Im getting a classCastException
我得到一个 classCastException
Exception in thread "main" java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date
I can't see the problem?
我看不出问题?
回答by WhiteFang34
You're importing java.sql.Date
instead of java.util.Date
.
您正在导入java.sql.Date
而不是java.util.Date
.
回答by andersoj
You have
你有
import java.sql.Date
somewhere up top. Gotta be careful about the two Date
classes; they aren't interchangeable.
某处顶部。必须小心这两个Date
类;它们不可互换。
回答by Kevin
Hello try to use java.util.Date instead just Date:
你好,尝试使用 java.util.Date 而不是 Date:
Java.util.DateFormat df = new SimpleDateFormat("dd/mm/yyyy");
Java.util.Date date1 = null, date2 = null;
String start, finish;
System.out.println("Please enter a start date:");
while(date1 == null){
try{
start = scan.next();
date1 = (Java.util.Date) df.parse(start);
}catch(ParseException e){
System.out.println("Please enter a valid date!");
}
}