【问题标题】:JAVA - if condition not working properly on parameterJAVA - 如果条件在参数上不能正常工作
【发布时间】: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);
}

【问题讨论】:

  • 我建议你不要使用TimestampSimpleDateFormatDate。这些类设计不佳且早已过时,SimpleDateFormat 特别是出了名的麻烦。而是使用LocalTime 和/或java.time, the modern Java date and time API 中的其他类。

标签: java date calendar simpledateformat date-format


【解决方案1】:

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

这实际上将日期解析为 Jan 1st 1970。因此,如果您将其与当前时间进行比较,它将始终在之后。这就是您的 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
}

【讨论】:

  • 感谢它现在工作,但如何在条件中添加分钟。比如我把迟到时间改成10:35?
  • 您可以使用相同的方法。使用 Calendar.MINUTE 并获取当前分钟。
  • 好的,再次感谢您的帮助!
  • @Octavio - 您可以使用 Ole V.V. 建议的现代日期时间 API (java.time API) 来摆脱所有这些容易出错的复杂性和开销。我强烈建议你听从他的建议。
  • 好的,我试试看。谢谢!
【解决方案2】:

java.time

我建议您使用现代 Java 日期和时间 API java.time 来处理日期和时间。

如果您确定日期相同,并且只需要比较一天中的时间,那么您需要以下内容。让我们首先声明一个常量来保持上午 10 点的阈值:

private static final LocalTime DUE_TIME = LocalTime.of(10, 0);

现在进行比较:

    LocalTime now = LocalTime.now(ZoneId.systemDefault());
    if (now.isAfter(DUE_TIME)) {
        System.out.println("Late");
    } else {
        System.out.println("On time");
    }

刚刚运行时(我的时区是 12:42),我得到了这个输出:

迟到

LocalTime 是没有日期的时间(并且没有时区或 UTC 偏移量)。它从 00:00 到 23:59:59.999999999。因此,从 00:00 到 10:00 的每次时间都将被视为准时,而一天中的所有其他时间都将被视为迟到。

链接

【讨论】:

  • 我也试试这个。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-13
相关资源
最近更新 更多