问题
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.
Edit: I thought perhaps it would help if I added the bit of code that is calling this so maybe it will be more clear how I am trying to use it, so here is the addAppointment() method, so you can see where getDay() is being called and where it's going.
public static void addAppointment() throws SQLException
{
//get the info
String desc = getDesc();
java.sql.Date apptDay = getDay();
Time[] times = getTime();
Time startTime = times[0];
Time endTime = times[1];
int key;
Connection conn = SimpleDataSource.getConnection(); //connect to the database
try
{
PreparedStatement max = conn.prepareStatement("SELECT MAX(ID) FROM Calendar");
ResultSet result = max.executeQuery();
key = result.getInt("ID") + 1;
PreparedStatement stat = conn.prepareStatement(
"INSERT INTO Calendar " +
"VALUES (?, ?, ?, ?, ?)");
stat.setInt(1, key);
stat.setString(2, desc);
stat.setDate(3, apptDay);
stat.setTime(4, startTime);
stat.setTime(5, endTime);
stat.execute();
System.out.println("\nAppointment added!\n");
}
finally
{
conn.close(); //finished with the database
}
}
回答1:
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.
回答2:
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;
}
回答3:
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.
回答4:
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());
回答5:
sqlDate = new java.sql.Date(apptDay.getTime());
回答6:
Date.valueOf(scanner.nextLine())
回答7:
String strDate = scanner.nextLine();
SimpleDateFormat format= new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date = format.parse(strDate);
回答8:
Try below method -
private static java.sql.Date getDay() throws SQLException {
Scanner in = new Scanner(System.in);
String input;
java.util.Date utilDay = null;
DateFormat df = new SimpleDateFormat("yyyy-mm-dd");
System.out.println("\nPlease enter the date of the appointment, format: yyyy-mm-dd");
while(utilDay == null){
try{
input = in.next();
utilDay = (java.util.Date) df.parse(input);
}catch(ParseException e){
System.out.println("Please enter a valid date! Format is yyyy/mm/dd");
}
}
java.sql.Date sqlDate = new java.sql.Date(utilDay.getTime());
return sqlDate;
}
And from main()
method, call this method -
Date birthday = getDay();
回答9:
java.time
It’s time someone writes the modern answer to this question.
Assuming that you are using (or can start using) a JDBC 4.2 compliant driver you should not use the two Date
classes nor DateFormat
or SimpleDateFormat
. All those classes are poorly designed, the last two particularly troublesome. They are also long outdated. Instead rely on java.time, the modern Java date and time API. It’s much nicer to work with. We need a LocalDate
and a DateTimeFormatter
.
Now we’re at it, don’t use java.sql.Time
either. Use LocalTime
from java.time.
So your variable declarations become:
//get the info
String desc = getDesc();
LocalDate apptDay = getDay();
LocalTime[] times = getTime();
LocalTime startTime = times[0];
LocalTime endTime = times[1];
int key;
Only for passing the java.time objects to your prepared statement you don’t use setDate
and setTime
. You need to use setObject
:
stat.setInt(1, key);
stat.setString(2, desc);
stat.setObject(3, apptDay);
stat.setObject(4, startTime);
stat.setObject(5, endTime);
stat.execute();
Everything else is as before. For parsing the user input string to a LocalDate
, here is a short demonstration:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy/M/d");
String input = "2019/11/09";
try {
LocalDate aptDate = LocalDate.parse(input, dateFormatter);
System.out.println("Parsed date: " + aptDate);
} catch (DateTimeParseException dtpe) {
System.out.println("Please enter a valid date. Format is yyyy/mm/dd");
}
The output from the last snippet is:
Parsed date: 2019-11-09
I have specified just one M
and one d
in the format pattern string to allow the user to enter one or two digits for month and day of month, for example 2019/11/9
. Most users I know will appreciate this.
Link
- Oracle tutorial: Date Time explaining how to use java.time.
来源:https://stackoverflow.com/questions/18438587/string-to-java-sql-date