Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast string to date Java

Tags:

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 = (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?

like image 480
user195257 Avatar asked Mar 16 '26 20:03

user195257


2 Answers

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

like image 60
WhiteFang34 Avatar answered Mar 19 '26 08:03

WhiteFang34


You have

import java.sql.Date 

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

like image 42
andersoj Avatar answered Mar 19 '26 08:03

andersoj