Link to home
Start Free TrialLog in
Avatar of ctlo
ctlo

asked on

Cannot compare 2 date

I have folllowing code:
  if(rs.next()){
                rs.getString("last_upd_date");
                SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
                Date lastDate = df.parse(rs.getString("last_upd_date"));
                System.out.println("lastDate : " + lastDate.toString() + "  date " + date);

                //result = lastDate.before(date);
                System.out.println("result " + date.after(lastDate) + " " + date.equals(lastDate) +" " date.before(lastDate));
                result = (date.after(lastDate) && !date.equals(lastDate));
                System.out.println("result " + result);
            }

the result is :
lastDate : Tue Mar 12 10:35:15 CST 2002  date Tue Mar 12 10:35:15 CST 2002
result true false false


Although the I print the string of date and lastDate with same value, it cannot compare they are equal and after.
why? how to correct?
Avatar of Peter Kwan
Peter Kwan
Flag of Hong Kong image

What is your definition of variable "date"?
Avatar of cini_gm
cini_gm

You are not specified about the 'date'. Convert the 'date' variable also to the same format. ie, the format u specified in the SimpleDateFormat.
you only show to second. The variable "date" might have some extra milliseconds that make it "after" the value of "lastDate"
What means with miliseconds is the code of java.util.Date.equals(Object), it says:

...
return obj instanceof Date && getTime() == ((Date) obj).getTime();
...

Verify if you date have (date1.getTime() == date2.getTime()).

Or visualy do System.out.println(date1.getTime() + "--" + date2.getTime()
Avatar of ctlo

ASKER

If I also want to compare the 2 days is after or beofre , what can I do ?
P.S the definition of variable "date" is also Date with SimpleDateFormat df .
thx
ASKER CERTIFIED SOLUTION
Avatar of sandro901
sandro901

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial