The Calendar() class, comparing two times?

Hi i recently asked on EE which is the best class for time management, the reply i got was Calendar class, i am able to input times and create an instance of this class, however i get totally lost when i need to compare them?

Is there any easy way of comparing two times? For example;

time1 > time2

Or is there a specific method that Calendar class provides for this? If so, how would i go about using it? So far i have had no luck! Any help would be much appreciated. Thank you.

Mr S.M.
Who is Participating?
imladrisConnect With a Mentor Commented:
The Calendar class has a before and an after method that can be used for comparisons.

public boolean before(Object when);
public boolean after(Object when);
Mayank SAssociate Director - Product EngineeringCommented:
Check the Calendar API specifications for more:
easiest way to compare time is through getTimeInMillis() method of Calendar class.
simple long subtraction.
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.

Mayank SAssociate Director - Product EngineeringCommented:
Performance-wise - No. Because it would result in two method calls rather than one method-call in case of before () or after () or equals ().

Calendar a,b;
//initialize a and b with your time...

a.getTimeInMillis() > b.getTimeInMillis() //compare

Mayank SAssociate Director - Product EngineeringCommented:
Yeah, that's what.... it has 2 method calls. One getTimeInMillis () for a, and one for b. Its better to use after () or before() or equals () depending upon the situation.

--> a.getTimeInMillis() > b.getTimeInMillis() //compare

Yes that will work, but isn't:
Just so much more readable!

--> Yeah, that's what.... it has 2 method calls
When you call a.after(b) it will do exactly the same number of calls (in fact one more for the delegation, and another for the cast), but as stated above, it is just a lot easier to read, which is more important than the sub-microsecond improvement in performance.
Programmer_to_beAuthor Commented:
Thanks everyone, all the methods suggested work great thank you.
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.

All Courses

From novice to tech pro — start learning today.