1

Currently I'm trying to find out whether a certain time is between a startTime-1 Hour and endTime.

Currently my code is :

if (localTimeNow.isAfter(startShift.minus(1, ChronoUnit.HOURS)) &&
        localTimeNow.isBefore(endShift)) {
    Toast.makeText(this, "In shift", Toast.LENGTH_SHORT).show();
} else {
    Toast.makeText(this, "Not in shift", Toast.LENGTH_SHORT).show();
}

This would work well if, let's say the startShift is at 08:00 and endShift at 16:00, but this doesn't work when I put startShift at 22:00 and endShift at 06:00.

Any suggestion on the logic here?

Kevin Murvie
  • 2,592
  • 1
  • 25
  • 43
  • Did you check [this](https://stackoverflow.com/a/64935458/4694013) – Anoop M Maddasseri Sep 04 '21 at 16:30
  • 1
    Ah I actually had a method similar like this but wasn't as clean! Thanks! Their solution is really nice too, guess you should post this as an answer quoting their answer, just in case someone comes across my question while querying – Kevin Murvie Sep 04 '21 at 16:49

1 Answers1

1

Posting this as an answer as suggested. Here is a solution for the Midnight Problem, It works as intended even when the interval spans across midnight.

/**
 * Takes into consideration that the interval may span accross midnight
 *
 * @param clock to make unit testing easier, just replace for Clock.systemUTC() in your code 
 * @param start the interval start
 * @param end the interval end
 * @return true if "now" is inside the specified interval
 */
static boolean isNowBetweenLocalTime(Clock clock, final LocalTime start, final LocalTime end) {
    LocalTime now = LocalTime.now(clock);

    // if interval crosses midnight
    if (end.isBefore(start)) {
        if (now.isAfter(start) && now.isAfter(end)) {
            return true;
        }
        if (now.isBefore(start) && now.isBefore(end)) {
            return true;
        }
        return false;
    }

    // if interval does not cross midnight
    if (end.isAfter(start)) {
        if (now.isAfter(start) && now.isBefore(end)) {
            return true;
        }
        return false;
    }

    return false; // interval is 0 so start and end always outside interval
}

Original Post - https://stackoverflow.com/a/64935458/4694013

Anoop M Maddasseri
  • 10,213
  • 3
  • 52
  • 73