String to java.sql.Date

The following statement caused the error:

apptDay = (java.sql.Date) df.parse(input);

In fact, the type of the return value of java.text.DateFormat.parse(String) is java.util.Date, which is incomparable with java.sql.Date.

In your situation, the easiest way might be using java.util.Date instead of java.sql.Date.

Another note: your class name Calendar is duplicate with java.util.Calendar. And it is not a good coding style to use class names which are already used by the standard library.


java.sql.Date and java.util.Date are two different Classes. You need to convert the sql date into util date which is compatible with Calendar.

  Date jDate =  new Date(sqlDate.getTime());

and vice-versa

  java.sql.Date sqlDate =  new java.sql.Date(jDate.getTime());

It would be much simpler to change the input format to yyyy-MM-dd and use java.sql.Date.valueOf(String date) method which converts a string in the above format to a java.sql.Date value directly.


This should work:

private static java.sql.Date getDay()
{
    Scanner in = new Scanner(System.in);
    String input;
    Date apptDay = null;
    DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
    java.sql.Date sqlDate;
    System.out.println("\nPlease enter the date of the appointment, format: yyyy/mm/dd");
    while(apptDay == null)
    {
        try
        {
            input = in.next();
            apptDay = (Date) df.parse(input);
        }
        catch(ParseException e)
        {
            System.out.println("Please enter a valid date! Format is yyyy/mm/dd");
        }
    }
    sqlDate = new java.sql.Date(apptDay.getTime());
    return sqlDate;
}