Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 221
  • Last Modified:

Date Object comparison

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

0
roshanmatre
Asked:
roshanmatre
  • 2
  • 2
  • 2
  • +2
2 Solutions
 
CEHJCommented:
long diff = date1.getTime() - date2.getTime(); // diff in ms
0
 
bcsonkaCommented:
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
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 2
  • 2
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now