Date Object comparison

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

roshanmatreAsked:
Who is Participating?
 
CEHJConnect With a Mentor Commented:
long diff = date1.getTime() - date2.getTime(); // diff in ms
0
 
bcsonkaConnect With a Mentor Commented:
Here's a link to a few simple examples . . .

http://www.javaalmanac.com/egs/java.util/CompDates.html
0
 
bcsonkaCommented:
Just a reminder, the examples above are for Calendar objects.  May or may not help you.  But worth a look.
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
ipamanCommented:
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
}
0
 
zzynxSoftware engineerCommented:
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!)
0
 
ipamanCommented:
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.
0
 
RuadRauFlessaCommented:
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.
0
 
CEHJCommented:
:-)
0
All Courses

From novice to tech pro — start learning today.