user195257
user195257

Reputation: 3316

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

Upvotes: 2

Views: 17506

Answers (3)

Kevin
Kevin

Reputation: 570

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

Upvotes: 0

andersoj
andersoj

Reputation: 22884

You have

import java.sql.Date 

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

Upvotes: 3

WhiteFang34
WhiteFang34

Reputation: 72049

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

Upvotes: 16

Related Questions