0

I'm getting two times (in the format HH:mm aa) say 6:00 pm to 5:00 pm.I need some generic and shortest way to compare these two times.

For instance:-

Say I am comparing 4pm and 7pm, then I should be getting 4pm > 7pm, since my start time is 6pm and end time is 5pm

Please help.

user3115056
  • 1,266
  • 1
  • 10
  • 25
  • Have you had a look at the javadoc of `Date`? – fge Mar 04 '14 at 12:50
  • Yes I did see the util.Date which has before and after however that applies to start and end time in a specific day. i.e. 12.00 am to 11:59 am – user3115056 Mar 04 '14 at 12:51
  • possible duplicate of [Calculate Difference between two times in Android](http://stackoverflow.com/questions/14110621/calculate-difference-between-two-times-in-android) – Raedwald Mar 05 '14 at 08:15

3 Answers3

1
         // Per the JavaDoc:
         // the value 0 if the argument Date is equal to this Date; a value 
         // less than 0 if this 
         // Date is before the Date argument; and a value greater
         // than 0 if this Date is after 
         // the Date argument.

         if (startDate.compareTo(endDate) < 0)
         {
            // before
         }
         else if (startDate.compareTo(endDate) == 0)
         {
            // same
         }
         else if (startDate.compareTo(endDate) > 0)
         {
            // after
         }
         else if (startDate.compareTo(firstDate) > 0 && startDate.compareTo(secondDate) < 0)
         {
            // between
         }

Insert your conditions as appropriate.

Engineer2021
  • 3,288
  • 6
  • 29
  • 51
1

The java.util.Date and .Calendar classes built into Java are notoriously troublesome. Instead use either the Joda-Time library or the new java.time package in Java 8 (inspired by Joda-Time, defined by JSR 310).

Joda-Time

Joda-Time has built-in support for the Java Comparator. And Joda-Time offers its own comparison methods: isBefore, isBeforeNow, isAfter, isAfterNow, isEqual.

Example Code

DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime now = new DateTime( timeZone );
DateTime yesterday = now.minusDays( 1 );
boolean isYesterdayBeforeNow = yesterday.isBefore( now ); // TRUE.

java.time

In the java.time package, a ZonedDateTime offers methods such as isBefore and isAfter.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

Date has before and after methods and can be compared to each other.

so you could do something like this:

if(todayDate.after(historyDate) && todayDate.before(futureDate)) {
    // In between
}
Salah
  • 8,567
  • 3
  • 26
  • 43
  • I said there are 2 times within 6:pm to 5pm... Say I am comparing 4pm and 7pm, then I should be getting 4pm > 7pm, since my start time is 6pm and end time is 5pm. – user3115056 Mar 04 '14 at 12:52
  • you can override `compareTo()` method and adjust the `return` type to suit your need (specify 4 is greater than 6) – KNU Mar 04 '14 at 13:03