Question

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.

No correct solution

OTHER TIPS

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

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.

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
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top