Home > Mobile >  Check if a LocalDateTime is between work hours
Check if a LocalDateTime is between work hours

Time:01-09

I wonder what's the more efficient way to compare values to check if the current date is in a range of values.

I'd like to trigger a local notification only from Monday to Friday and from 8:00 to 18:00 (8a.m. - 6p.m.)

First I was writing this :

val current = LocalDateTime.now()
val day = current.dayOfWeek.value
val hour = current.hour

if(day != 6 && day != 7 && hour > 7 && hour < 18) 
   {...}

But Android Studio suggested hour in 8..17

So should I use day != 6 && day != 7 && hour > 7 && hour < 18 Or day != 6 && day != 7 && hour in 8..17, Or day in 1..5 && hour in 8..17, Or something else?

What do you think?

CodePudding user response:

Of the many ways you do this, you won't observe any as being "more efficient" (unless you are doing millions of evaluations).

I agree with @Tenfour04 that a much bigger consideration is readability - so that you/others can reason that the code is correct. Consider also using named constants for the days of the week (DayOfWeek.MONDAY) you can still use these in ranges. How about this then:

val current = LocalDateTime.now()
val isInWorkingHours = current.hour in 8..17
val isWorkingDay = current.dayOfWeek in DayOfWeek.MONDAY..DayOfWeek.FRIDAY
if(isInWorkingHours && isWorkingDay) {
    //
}

And with an IDE like IntelliJ you get hints so that .. range syntax is easily to understand you get: enter image description here

  • Related