I'm developing a java program and I wish to input date from user.
For this I have used a JSpinner and set it's model type as Date from Spinner Model Editor.
Also, by default the spinner also displays time with its and I don't want time, but only date thus, I created a new SimpleDateFormat and applied to spinner.
Here's the code for SimpleDateFormat :-
SimpleDateFormat date_format = new SimpleDateFormat("dd-MM-yyyy");
dateSpinner.setEditor(new JSpinner.DateEditor(dateSpinner,date_format.toPattern()));
I used DateFormat becuase I want to display the date in dd-mm-yyyy format.
After that I used stateChanged Method to fetch the date selected by user via JSpinner.
The body of method is as follows :-
private void stateChanged(javax.swing.event.ChangeEvent evt) {
Date dateChosen = (Date) dateSpinner.getValue();
int date = dateChosen.getDate();
int month = ( dateChosen.getMonth() ) + 1;
int year = ( dateChosen.getYear() ) + 1900;
String DB_Date = String.valueOf(year) + "-" + String.valueOf(month) + "-" + String.valueOf(date);
// 1 was added to **month** because month's were 1 less than the conventional human format
// also, 1900 was added to **year** to make it suitable for apperance of human conventions
}
Now, I wish to input this date from user to my MySQL database column whose data type is DATE.
For this, i tried the following :-
1. I tried to use the setDate( ) method with its parameter as dateChosen, whose code is as follows :-
PreparedStatement stmt = new PreparedStatement();
stmt.setDate (column_no, (java.sql.Date) dateChosen);
But instead the date was not stored and the date column of MySQL table was left blank.
.
2. I tried to use the setString( ) method with its parameter as DB_Date, whose code is as follow :-
PreparedStatement stmt = new PreparedStatemnt();
stmt.setString (column_no, DB_Date);
But, again the (date) column of MySQL table was left blank.
Now, I want to know how can I store the date from JSpinner to my MySQL table column whose data type is DATE.
Also, if the there is any other approach than using JSpinner to store the date in MySQL table then please tell me that too.
The Date
type in JDBC
is java.sql.Date
and in other case is java.util.Date
,they are not the same and can not be convert directly
You can try with below code
PreparedStatement stmt = new PreparedStatement();
stmt.setDate (column_no, new java.sql.Date(dateChosen.getTime()));
BTW,if you are using java-8
and jdbc-4
,the more suitable way is to use LocalDate
stmt.setDate (column_no, localDate.now());