我正在开发一个Java程序,希望从用户输入日期。
为此,我使用了JSpinner并将其模型类型从Spinner Model Editor中设置为Date。
另外,默认情况下,微调器还显示带有时间的时间,并且我不想显示时间,而是只显示日期,因此,我创建了一个新的SimpleDateFormat并将其应用于微调器。
这是SimpleDateFormat的代码:-
SimpleDateFormat date_format = new SimpleDateFormat("dd-MM-yyyy");
dateSpinner.setEditor(new JSpinner.DateEditor(dateSpinner,date_format.toPattern()));
我使用DateFormat是因为我想以dd-mm-yyyy格式显示日期。
之后,我使用stateChanged方法来获取用户通过JSpinner选择的日期。
方法的主体如下:
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
}
现在,我希望将此日期从用户输入到数据类型为DATE的MySQL数据库列中。
为此,我尝试了以下操作:-1
.我尝试使用setDate()方法,其参数为dateChosen,其代码如下:-
PreparedStatement stmt = new PreparedStatement();
stmt.setDate (column_no, (java.sql.Date) dateChosen);
但是,日期没有存储,MySQL表的date列留为空白。
。
2.我尝试使用setString()方法,其参数为DB_Date,其代码如下:-
PreparedStatement stmt = new PreparedStatemnt();
stmt.setString (column_no, DB_Date);
但是,MySQL表的(date)列再次留为空白。
现在,我想知道如何将日期从JSpinner存储到数据类型为DATE的MySQL表列中。
另外,如果除了使用JSpinner将日期存储在MySQL表中之外,还有其他方法,请也告诉我。
相关分类