JAVA – if condition not working properly on parameter

huangapple go评论57阅读模式
英文:

JAVA - if condition not working properly on parameter

问题

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);
}
英文:

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

答案1

得分: 3

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

这实际上将日期解析为 1970年1月1日。因此,如果你将其与当前时间进行比较,它将始终在之后。这就是你的if条件始终为真的原因。

相反地,你可以使用以下代码获取当前小时。

Calendar rightNow = Calendar.getInstance();
int hour = rightNow.get(Calendar.HOUR_OF_DAY); // 小时以24小时制表示。

你可以使用这个值与你的10:00(如果是上午,则为10;如果是下午,则为22)的时间限制进行比较。确保在比较之前转换为24小时制。

因此,代码会类似于

if (hour > 22) {
    // 时间太晚
} else {
    // 时间不晚
}
英文:

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
}

答案2

得分: 3

java.time

我建议您使用java.time,这是现代的Java日期和时间API,用于处理日期和时间。

如果您确定日期相同,只需比较每天的时间,以下是您需要的内容。让我们首先声明一个常量来保存您的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("迟到了");
} else {
    System.out.println("准时");
}

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

迟到了

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

链接

英文:

java.time

I recommend you use java.time, the modern Java date and time API, for your date and time work.

If you’re sure that the date is the same and you only need to compare the time of day, the following is what you need. Let’s first declare a constant to hold your threshold of 10 AM:

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

Now the comparison goes:

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

When running just now (12:42 in my time zone), I got this output:

> Late

LocalTime is a time of day without date (and without time zone or UTC offset). It goes from 00:00 to 23:59:59.999999999. So every time from 00:00 through 10:00 will be considered on time and all other times of day late.

huangapple
  • 本文由 发表于 2020年10月4日 10:30:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/64190657.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定