Monday, 26 August 2013

String to java.sql.Date

String to java.sql.Date

I realize this has been asked a lot. I did actually look. I've spent hours
looking around and trying to figure this out. I'm supposed to be making a
program that stores what amounts to a list of appointments in a database,
with a description, date, start time, and end time. It has to take input
from the user to add or cancel appointments, so as far as I know that
means I need to convert a string to a date.
These are my imports: import java.io.File; import java.io.IOException;
import java.sql.Connection; import java.sql.Date; import
java.sql.PreparedStatement; import java.sql.ResultSet; import
java.sql.ResultSetMetaData; import java.sql.SQLException; import
java.sql.Time; import java.text.DateFormat; import
java.text.ParseException; import java.text.SimpleDateFormat; import
java.util.ArrayList; import java.util.Scanner;
As you can see, no java.util.Date there. Here is the bit where I'm getting
the error:
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 Date(apptDay.getTime());
return sqlDate;
}
I've added java.sql.Dates to it and mucked about with it a bunch trying to
get it to work, but it's still giving me this:
Exception in thread "main" java.lang.ClassCastException: java.util.Date
cannot be cast to java.sql.Date at Calendar.getDay(Calendar.java:47)
Any ideas on what I'm doing wrong or how to make this work would be very
much appreciated.

No comments:

Post a Comment