Skip to content Skip to sidebar Skip to footer

Determining If Time Is Between Two Other Times Regardless Of Date

I have the following code private boolean checkIfTimeInBetweenRegardlessOfDate(long timeOne, long timeTwo) { final Calendar firstCalendar = Calendar.getInstance();

Solution 1:

If your want to compare time-of-day to minute precision, get the minute-of-day value from each, i.e. minuteOfDay = hourOfDay * 60 + minuteOfHour, then compare those.

You can extend that to second or millisecond as needed.

Since you want 6:00pm and 2:00am to cover 8pm, you need to detect an inverted time range.

All in all, you can do it like this:

privatestatic boolean isTimeInRange(long currentMillis, long fromMillis, long toMillis) {
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(currentMillis);
    int currentMinuteOfDay = cal.get(Calendar.HOUR_OF_DAY) * 60 + cal.get(Calendar.MINUTE);
    cal.setTimeInMillis(fromMillis);
    int fromMinuteOfDay = cal.get(Calendar.HOUR_OF_DAY) * 60 + cal.get(Calendar.MINUTE);
    cal.setTimeInMillis(toMillis);
    int toMinuteOfDay = cal.get(Calendar.HOUR_OF_DAY) * 60 + cal.get(Calendar.MINUTE);
    if (fromMinuteOfDay <= toMinuteOfDay)
        return (currentMinuteOfDay >= fromMinuteOfDay && currentMinuteOfDay < toMinuteOfDay);
    return (currentMinuteOfDay >= fromMinuteOfDay || currentMinuteOfDay < toMinuteOfDay);
}

Post a Comment for "Determining If Time Is Between Two Other Times Regardless Of Date"