Time range that crosses midnight?

What’s the best way to determine if the current time of day is between two values, specifically when those values cross midnight? For example:
`if (currentTime is between 8PM and 3AM)`

I’ve tried `timeOfDayIsBetween`, but it seems to compare the full DateTime object. So something like this:
`timeOfDayIsBetween(timeToday("20:00"), timeToday("03:00"), new Date(), location.timeZone)` return true when the current time is between 3AM and 8PM, rather than the other way around. (I may be wrong about that, but I think that’s what I’ve seen so far.)

I’ve done more complicated things like this:

``````def startToday = timeToday("20:00")
def endToday = timeToday("03:00")
if (endToday <= startToday) {
use (TimeCategory) {
endToday = endToday + 1.day
}
}

if (timeOfDayIsBetween(startToday, endToday, new Date(), location.timeZone)
``````

But that seems like overkill. Is there an easier way to do this?

``````Boolean getTimeOk(firstTime, secondTime) {
long currtime = now()
long start = timeToday(firstTime, location.timeZone).time
long stop = timeToday(secondTime, location.timeZone).time
(start == stop && currTime >= start && currTime - start < 60000) || (start <= stop ? currTime >= start && currTime < stop : currTime < stop || currTime >= start)
}
``````

It always does seem like overkill. Toss in sunrise and sunset and it gets even messier.

3 Likes

Ha, excellent! Thank you, sir. I’m sad there isn’t a built-in solution, but I’ll accept yours as the best available.

There may exist some easier way to do it. But I don't spend any time looking for it.

In webCoRE it helps sometimes to use the opposite condition when the times span midnight. That is, if the current time is NOT between 03:00 and 20:00 (which IS between 20:00 and 03:00, spanning midnight). That keeps the start and end times on the same day. Just a thought. Not sure if that helps.

1 Like