T. Akhayo
T. Akhayo

Reputation: 411

Is hour in time range that spans 2 days?

I've got a function which may only execute within a specific time range. The user can specify this time range by entering a start and end hour.

The problem i bumped into is when the time range spans days. For example: start range hour: 18 (18:00 6 pm) end range hour: 6 (06:00 6 am)

A simple:

if( hour >= startrange && hour <= endrange ) { now in range }

doesn't work in this case.

I'm finding it hard to come up with a solution for this problem. Maybe my mind had enough for today. ( ;) )

Can anybody can point me to a direction?

Upvotes: 1

Views: 265

Answers (2)

towi_parallelism
towi_parallelism

Reputation: 1481

If the startrange > endrange, you have to change the if clause. So:

if (startrange > endrange) {
    if (hour > startrange`) hour = hour -24;
    startrang = startrange -24;
}
if( hour >= startrange && hour <= endrange ) { now in range }

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1501033

Firstly, I'd use Joda Time and its LocalTime type to represent the times. You can then do:

static boolean isInRange(LocalTime start, LocalTime end, LocalTime value) {
    // Avoid equality problems - see description
    if (value.equals(start) || value.equals(end)) {
        return true;
    }
    if (start.compareTo(end) > 0) {
        return !isInRange(end, start, value);
    }
    return start.compareTo(value) < 0 && value.compareTo(end) < 0;
}

In other words, you'd generally only end up doing the final comparison with value when you'd got a start/end range where start <= end - but if you start off with the other way round, then you just invert the result of doing the reverse comparison.

In other words, something is in the range (10pm, 2am) if it's not in the range (2am, 10pm).

Alternatively, you could avoid the recursive call:

static boolean isInRange(LocalTime start, LocalTime end, LocalTime value) {
    return start.compareTo(end) > 0
        // Reversed: if it's earlier than the end point, or later than the start
        ? value.compareTo(end) <= 0 || start.compareTo(value) <= 0
        : start.compareTo(value) <= 0 && value.compareTo(end) <= 0;
}

The tricky bit is equality. The code above assumes that the start/end points are both inclusive, either way round. If you want anything else, you'll need to think very carefully about every situation.

Upvotes: 0

Related Questions