• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1864
  • Last Modified:

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.
0
Programmer_to_be
Asked:
Programmer_to_be
1 Solution
 
imladrisCommented:
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);
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Check the Calendar API specifications for more:

http://java.sun.com/j2se/1.4.1/docs/api/java/util/Calendar.html
0
 
tapasviCommented:
easiest way to compare time is through getTimeInMillis() method of Calendar class.
simple long subtraction.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
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 ().

Mayank.
0
 
tapasviCommented:
Calendar a,b;
//initialize a and b with your time...

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

0
 
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.

Mayank.
0
 
grim_toasterCommented:
--> a.getTimeInMillis() > b.getTimeInMillis() //compare

Yes that will work, but isn't:
a.after(b);
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.
0
 
Programmer_to_beAuthor Commented:
Thanks everyone, all the methods suggested work great thank you.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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