Codes for getting current date:
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
Date now = new Date();
String strDate = sdfDate.format(now);
return strDate;
Codes to search date and return result
try
{
String x = cDate();
ps = conn.prepareStatement(fill);
rs = ps.executeQuery();
int count = 0;
while (rs.next()){
Date dDate = rs.getDate("recDate");
if (x.equals(dDate)){
System.out.println("True);
break;
}
else {
System.out.println("False");
}
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
Codes below to search names and return result
try
{
string attendant = txtName.getText();
ps = conn.prepareStatement(fill);
rs = ps.executeQuery();
int count = 0;
while (rs.next()){
String bName = rs.getString("name");
if (attendant.equals(bName){
System.out.println("True);
break;
}
else {
System.out.println("False");
}
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
I manged to get my 2nd code which is to search name and return result to work nicely. But as for the date search, it result false even I have the getDate() in SQL DB.
I did a System.out.println(x) and System.out.println(dDate) to verify the format but it turn out to be correct.
2013-01-17
2013-01-17
which should return “True”
Edited:
java.util.Date now = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(now.getTime());
I replace (x.equals(dDate)) to (sqlDate == dDate) but the result still return as false, any idea?
Please help..
Finally I got it..
Solution
(Math.round(now.getTime() / 1000/3600/24) == Math.round(dDate.getTime() /1000/3600/24)
Java Date contains time information also. Dates could differ in minutes or even seconds. To make sure both dates has exactly the same value you should print out
date.getTime()which returnlongvalue of milliseconds sinceJanuary 1, 1970, 00:00:00 GMT. If you wanna compare you should convertxfrom String to Date and then do this:however, if you wanna compare just year, month and day you should trunk like this:
More about Date comparision in Java you can find here: Date Comparison using Java