[英]Get Date object from MySQL Database and show it on a formatted text field
我正在嘗試從數據庫中獲取出生日期,並將其顯示在JFormattedTextField上。 它應以mm / dd / yyyy格式顯示,但以yyyy / dd / mm格式存儲。 我將如何處理? 患者的出生日期存儲為java.sql.Date
JLabel lbl3 = new JLabel("Date of Birth:");
lbl3.setBounds(17, 129, 90, 22);
lbl3.setForeground(Color.WHITE);
lbl3.setFont(new Font("Microsoft New Tai Lue", Font.PLAIN, 16));
JFormattedTextField formattedDob = new JFormattedTextField();
formattedDob.setEditable(false);
formattedDob.setText("//");
formattedDob.setBounds(201, 128, 183, 22);
contentPane.add(formattedDob);
JButton btnSearchPatient = new JButton("Search");
btnSearchPatient.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
PatientSQL searchPatient = new PatientSQL();
Patient staff = searchPatient.getBySSN(patient.getSsn());
txtAddress1.setText(staff.getAddress1());
txtAddress2.setText(staff.getAddress2());
txtCity.setText(staff.getCity());
}
});
這是我的PatientSQL.java供參考(不相關的代碼(例如包和函數)已刪除,以便於閱讀):
public class PatientSQL {
private SessionFactory factory;
public PatientSQL() {
try {
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
}
/* Method to CREATE a patient in the database */
public void add(String fname, String lname, String ssn, java.sql.Date dob, String phoneNo, String address1, String address2, String city, String zipcode, String allergy1, String allergy2, String allergy3, String photo) {
Patient patient = new Patient(fname, lname, ssn, dob, phoneNo, address1, address2, city, zipcode, allergy1, allergy2, allergy3, photo);
add(patient);
}
public Patient getBySSN(String ssn) {
Session session = factory.openSession();
Patient patient = null;
try {
patient = (Patient) session.get(Patient.class, ssn);
} catch (HibernateException e) {
System.err.println("Can not find patient ssn: " + ssn);
} finally {
session.close();
}
return patient;
}
}
也許您應該嘗試將日期轉換為:使用LocalDateTime#parse()(如果字符串碰巧包含時區部分,則使用ZonedDateTime#parse())將特定模式的字符串解析為LocalDateTime。 喜歡:
String date_s = "2011/01/18";
SimpleDateFormat dt = new SimpleDateFormat("yyyy/dd/mm");
Date date = dt.parse(date_s);
SimpleDateFormat dt1 = new SimpleDateFormat("mm/dd/yyyy");
System.out.println(dt1.format(date));
愚蠢的要求要求愚蠢的答案:
CREATE TABLE patient (
...
dob_string VARCHAR(8),
dob_date DATE AS (STR_TO_DATE(dob_string,"%Y/%d/%m"))
)
因此,將其存儲到dob_string
,並從dob_date
獲取,然后根據需要輸出格式。
如果可以使用SimpleDateFormat
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
df.format(patient.getDob()); //I'm guessing what the get method is named but you get what I mean
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.