This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I am trying to get the result as a boolean value if one date input (e.g. 11/28/2006 03:50:44 PM) is less than or equal to the other input date (e.g. 11/28/2006 03:50:44 AM) using java.util.Calendar or java.util.GregorianCalendar. Would appreciate if I could get some pointers to do this.
In general, you can compare two objects if the class implements the Comparable interface. Then the class must implement a method called compareTo(). The method compareTo returns negative numbe for less than, zero for equals, and a positive number for greater than.
I believe that compareTo() is for the normal ordering and that if you want to use an alternative ordering, you implement the Compartor interface and implement a method called compare() that is like compareTo(), but takes two explicit parameters rather than an imiplicit parameter and one explicit paramater.
Anybody please correct me if I'm wrong.
Joined: Nov 03, 2003
Do I need to convert the date objects into milliseconds from the epoch then use either Calendar's 'equals' method or something like that? Any code snippet for this would be greatly appreciated?
If you have Date objects then you can call their after(Date) or before(Date) methods. No need for Calendar objects (unless this is some kind of homework assignment that says you must use Calendar objects).
There are many options. Unfortunately the equals() method won't help here - it tells you if the two times are equal, but it doesn't tell you whether one date is before or after the other. You can use compareTo() - if you look at the Calendar API you will see that Calendar already implements Comparable, and has a compareTo() method - so you don't need to convert to anything else. You certainly can convert to Date, and use Date's compareTo(), or you can convert to milliseconds (as a log) and do simple math. Theses options should all give you the same answer - choose whichever makes the most sense to you.
"I'm not back." - Bill Harding, Twister
Joined: Nov 03, 2003
Here what I have from the suggestions I got which seems to work well except for when I have AM or PM instead.