Link to home
Start Free TrialLog in
Avatar of roshanmatre
roshanmatre

asked on

Date Object comparison

hi,
can you please tell me how to find the difference between two date objects.

ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

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
SOLUTION
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
Avatar of bcsonka
bcsonka

Just a reminder, the examples above are for Calendar objects.  May or may not help you.  But worth a look.
java.util;

Date someDate1;
Date someDate2;

int diff = someDate1.compareTo(someDate2);

if( diff < 0 )
{
   //someDate1 is before someDate2
}

if( diff > 0 )
{
   //someDate2 is before someDate1
}

if( diff == 0 )
{
   //the dates are the same
}
ipaman,
roshanmatre,

If all you want to know is how the dates relate to each other, you better use the Date functions after(), before() and equals().

- someDate1.before(someDate2) returns true if someDate1 is before someDate2
- someDate1.after(someDate2) returns true if someDate1 is after someDate2
- someDate1.equals(someDate2) returns true if someDate1 equals someDate2 (to the millisecond!)
good point zzynx! either way will work. same amount of code. but I believe the compareTo() will be quicker at runtime. function is only called once.
ipaman that depends on what you want to do with it. If you only want to check one of them no problem then using those are fine. Otherwise use the compareTo() if you want to check for all of the cases. Oh and CEHJ's answer will be faster still cuz it basically does what the compareTo() method does but without that extra stack calls and such needed for the extra method.
:-)