gpt4 book ai didi

JAVA - 如果条件在参数上不能正常工作

转载 作者:行者123 更新时间:2023-12-01 23:45:53 24 4
gpt4 key购买 nike

我正在尝试制作一个提交按钮,在单击该按钮时保存用户输入,但我在 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);
}

最佳答案

你有行dateFormat.parse("10:00")

这实际上将日期解析为 1970 年 1 月 1 日。所以,如果你将它与当前时间进行比较,它总是会晚于。这就是您的 if 条件始终为真的原因。

相反,您可以使用以下代码获取当前时间。

Calendar rightNow = Calendar.getInstance();
int hour = rightNow.get(Calendar.HOUR_OF_DAY); //hour is in 24 hour format.

您可以使用此值将其与 10:00(上午 10 点,下午 22 点)的时钟限制进行比较。确保在比较之前转换为 24 小时格式。

所以,它会是这样的

if(hour > 22){
// Too late
}else{
// Not late
}

关于JAVA - 如果条件在参数上不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64190657/

24 4 0
文章推荐: unity3d - 无法使用 ARcore : Manifest Merger failed 在 Unity 2019.2.4f1 中构建 .APK
文章推荐: typescript - Typeguard 不会缩小类型
文章推荐: python - 从类 __init__() 调用静态方法导致 "takes 1 positional argument but 2 were given"TypeError
文章推荐: angular - 错误 :Property 'map' does not exist on type 'Observable