java中和当前日期比较,如何比较mySQL中的日期和java中的当前日期?

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";

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值