Search code examples
javadatecalendarsimpledateformatdate-format

JAVA - if condition not working properly on parameter


I am trying to make a submit button that saves the user input when it is clicked and I am having a problem with the if condition part. What I want to happen is when the user clicked the button after 10:00 o'clock (based on system time) the Report on database would be "Late" else report would be "Not Late". But every time I clicked the button even the system time is before 10:00 it always says "Late". How to fix this?

Code:

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);
}

Solution

  • You have the line dateFormat.parse("10:00").

    This actually parses the date as Jan 1st 1970. So, if you compare it against the current time it will always be after. That is the reason your if condition is always true.

    Instead, you can fetch the current hour using the below code.

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

    You can use this value to compare it with your 10:00 (10 if AM. 22 if PM) o'clock limit. Make sure you convert into 24-hour format before comparing.

    So, it would be something like

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