【发布时间】:2020-10-04 02:30:10
【问题描述】:
我正在尝试制作一个提交按钮,该按钮在单击时保存用户输入,但我遇到了 if 条件部分的问题。我想要发生的是当用户在 10:00 点之后(基于系统时间)单击按钮时,数据库报告将是“迟到”,否则报告将是“未迟到”。但每次我点击按钮时,即使系统时间在 10:00 之前,它总是说“迟到”。如何解决这个问题?
代码:
try {
String sql = "INSERT INTO studentregisterlogin" + "(SSN, TimeIn, TimeOut, Report)" + "VALUES (?,?,?,?)";
con = DriverManager.getConnection("jdbc:mysql://localhost/studentlogin", "root", "");
pst = con.prepareStatement(sql);
pst.setString(1, tfSerialNumber.getText());
pst.setTimestamp(2, new Timestamp(System.currentTimeMillis()));
pst.setString(3, " ");
// My Problem is this Condition
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
Date date = new Date(System.currentTimeMillis());
try {
if (date.after(dateFormat.parse("10:00"))) {
pst.setString(4, "Late");
} else if (date.before(dateFormat.parse("10:00"))){
pst.setString(4, "NotLate");
}
} catch (ParseException ex) {
Logger.getLogger(Menu.class.getName()).log(Level.SEVERE, null, ex);
}
pst.executeUpdate();
//updateTable();
} catch (SQLException | HeadlessException ex) {
JOptionPane.showMessageDialog(null, ex);
}
【问题讨论】:
-
我建议你不要使用
Timestamp、SimpleDateFormat和Date。这些类设计不佳且早已过时,SimpleDateFormat特别是出了名的麻烦。而是使用LocalTime和/或java.time, the modern Java date and time API 中的其他类。
标签: java date calendar simpledateformat date-format