I'm working on java swing program. to have date and store it's value in jtable i have been using Jdatechooser but it only works once when i run the file but after then it doesn't work and shows incorrect date.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date=sdf.format(jDateChooser2.getDate());
value in jtable
jDateChooser2.setDateFormatString((String) model.getValueAt(selectRow, 3));
code to store data in database :
String e_id;
String type = type_exp.getSelectedItem().toString();
String amount = amnt.getText();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(jDateChooser2.getDate());
String disc = disc_.getText();
try {
String sql = "insert into expance(type_expance,amount,exp_date,disc) values('" + type + "','" + amount + "','" + date + "','" + disc + "')"; //"++" use this pattern to pass variables
int n = st.executeUpdate(sql); //use this for insert/update/delte query and for searching ExecuteQuery
if (n == 1) {
JOptionPane.showMessageDialog(this, n + " records saved successfully..");
} else {
JOptionPane.showMessageDialog(this, "something went wrong");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
}
code to get values in jtable:
try {
String sql = "select * from expance";
rs = st.executeQuery(sql);
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(0);
while (rs.next()) {
model.addRow(new Object[]{rs.getString("e_id"), rs.getString("type_expance"), rs.getString("amount"), rs.getString("exp_date"), rs.getString("disc")});
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
}
You are setting the format not the date.
String pattern = "yyyy-MM-dd";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
Date date = simpleDateFormat.parse((String) model.getValueAt(selectRow, 3));
//Sets format
jDateChooser2.setDateFormatString(pattern );
//Sets the date
jDateChooser2.setDate(date );