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 "";
}
解决方案
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());
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)";
and then
else if (foundData.getBoolean("oldPasswd")) {
return "2";
}