将字符串转换为日期 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:25:14  来源:igfitidea点击:

Cast string to date Java

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.Dateinstead 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 Dateclasses; 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!");
        }
    }