gpt4 book ai didi

java - 从 MySQL 数据库获取日期对象并将其显示在格式化文本字段上

转载 作者:行者123 更新时间:2023-11-29 16:20:09 25 4
gpt4 key购买 nike

我正在尝试从数据库中获取出生日期并将其显示在 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));

关于java - 从 MySQL 数据库获取日期对象并将其显示在格式化文本字段上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54568332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com