开发者

Cast string to date Java

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 =开发者_如何学JAVA (Date) df.parse(start);
        }catch(ParseException e){
            System.out.println("Please enter a valid date!");
        }
    }

Im getting a classCastException

Exception in thread "main" java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date

I can't see the problem?


You're importing java.sql.Date instead of java.util.Date.


You have

import java.sql.Date 

somewhere up top. Gotta be careful about the two Date classes; they aren't interchangeable.


Hello try to use java.util.Date instead just 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!");
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜