What I Want to Do ?
I have a Class Customers that has a variable dob // Date of Birth
I am trying to take an input from the user using a java Swing Text Field.
Convert it into a java date and then convert into java.sql.Date, so that i can store it in my MySQL database.
This is the setter method for Customer class
public void setDOB(java.sql.Date dob)
{
DateOfBirth = dob;
}
Here is the code for my Swing Class(Application Window Loader)
//Date
if(textField_5.getText().isEmpty())
lblerr.setVisible(true);
else
{
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-YYYY");
Date dob = null;
dob = sdf.parse(textField_5.getText());
java.sql.Date sqlDate = new java.sql.Date(dob.getTime());
c1.setDOB(sqlDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
allinfoisentered = true;
}
textField_5 – is the Field Where User Inputs the Date.
I Tested My App With the following different inputs :
- 12-12-1993
- 10-05-1970
The Problem Is : The value that gets stored in MySQL Table is 1992-12-27, i have a strong feeling that this is some default date.
I want to know, How do i parse the string into Date and then send it to MySQL table.
(As discussed in comments…)
You have two problems:
More importantly (IMO) your error handling is incorrect. You’re using this
catchblock:… which means that even if parsing fails, you’ll insert all the data except the date, which wouldn’t have been set. You should have been able to get the information from the log files anyway, but presumably either you’re not logging
System.err, or you didn’t look at the logs.Error handling is very important. If an exception occurs when parsing the data, I would expect you not to want to insert the record at all – instead, the error should be propagated up the stack, forcing you to take note of it, and not losing the information. So you probably wanted something like this instead:
(Where
DataValidationExceptionis just a made-up exception – you should consider what you want to use consistently in your app.)Two things are vitally important when an error occurs: