Search code examples
javaandroidtimeandroid-calendarandroid-date

Comparing times: Check if a given time is within a certain amount of time of the another


As the title states; Is there a way to compare times to see if they are within a certain amount of time of each other? Ie. a way to tell if Time1 is within 15 minutes of Time2. A more complicated example might be within 75 minutes (because the hour will have changed as well, therefore resetting the minute count to 0.

There are lots of different ways of comparing dates and times in java/android. There is the Time class, Date class and Calendar class. There's even a compareTo method and a method to check if a date is before or after the other, but I can't find a solution to my problem.

Another example:

If I have a Time1, 12:30, and Time2 , 12:10, and I want to check if they are withing 15 minutes of each other. I can compare the difference of the difference of the minutes. 30 - 10 = 20. 20 is clearly not less than 15.

However, is Time1 was 12:56 and Time2 was 13:02, this method wouldn't work. 2 - 56 = -54, but the actual difference is 6. One solution is that if you know which time is later, check if the later minute is less greater than the earlier minute. If it isn't, then add 60 to the earlier minute.

Is this a good method of comparing? This will add lots of complexity to my code, especially as I need to check the hours and date as well. Is there a simpler solution or api that is available?


Solution

  • Use the timestamp (milliseconds since 1970) to check the difference of the dates.

    long timestamp1 = date1.getTime();
    long timestamp2 = date2.getTime();
    if (Math.abs(timestamp1 - timestamp2) < TimeUnit.MINUTES.toMillis(15)) {
        …
    }