如何比较mySQL中的日期和java中的当前日期? [英] How to compare a date from mySQL from the current date in java?
问题描述
我正在使用MVC模式在Java EE中编写一个简单的登录程序,我希望提醒用户他/她的密码已超过一年。目前我可以从数据库中获取数据,并将其转换为字符串,但之后我不知道如何将其与当前日期进行比较。
I am writing a simple log-in program in Java EE using the MVC pattern, and I wish to alert the user that his/her password is over a year old. Currently I can get the data from the database, and convert it into a string, but after that I don't know how to compare it to current date.
这是到目前为止我所拥有的:
This is what I have so far:
public String validateAccount(String email, String enterPassword) {
try {
Class.forName(driverName).newInstance();
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection connection;
try {
connection = DriverManager.getConnection(dbURL, username, password);
// Retrive current user data from database
String getCredentials = "SELECT id,dateSet,strength FROM users WHERE email=? AND hashPassword=SHA2(CONCAT(?, salt), 256)";
PreparedStatement verifyCredentials = connection
.prepareStatement(getCredentials);
verifyCredentials.setString(1, email);
verifyCredentials.setString(2, enterPassword);
ResultSet foundData = verifyCredentials.executeQuery();
while (foundData.next()) {
System.out.println("Found account");
int id = foundData.getInt("id");
String dateSet = foundData.getString("dateSet");
String strength = foundData.getString("strength");
// ... do something with these variables ... if
if (strength.equals("Weak")) {
return "1";
} else if (/*Check if the date in the database is over a year old, and return 2*/) {
return "2";
} else {
return "0";
}
}
foundData.close();
return "Account not found, re-enter your info again";
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
推荐答案
你可以使用foundData.getTimestamp()代替,并获取一个时间戳,你可以将其转换为普通的java数据类:)。
You can use foundData.getTimestamp() instead, and get a timestamp, which you can convert into a normal java Data class :)
所以,你会有像
So, you would have something like
Date dateSet = new Date(foundData.getTimestamp("dateSet").getTime());
或者,如果您不熟悉使用Date实例(您需要使用日历也可以直接在你的SQL查询中进行检查,
or alternatively, if you are not familiar with working with Date instances (you'll need to use a Calendar as well) you can do the check directly in your SQL query,
String getCredentials = "SELECT id,dateSet,strength, IF(dateSet < NOW() - INTERVAL 1 YEAR, TRUE, FALSE) AS oldPasswd FROM users WHERE email=? AND hashPassword=SHA2(CONCAT(?, salt), 256)";
然后
else if (foundData.getBoolean("oldPasswd")) {
return "2";
}
这篇关于如何比较mySQL中的日期和java中的当前日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!