Kevin Murvie
Kevin Murvie

Reputation: 2652

Android - Determining whether LocalTime is between a set of time (including past midnight and after midnight)

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?

Upvotes: 2

Views: 325

Answers (1)

Anoop M Maddasseri
Anoop M Maddasseri

Reputation: 10549

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

Upvotes: 2

Related Questions