I have found the following rule here in the community. It works fine when I have to execute the rule between a time in the morning and a time in the evening.
rule ButtonTimeOfDay
when
Item myitem received command
then
val LocalTime morning = new LocalTime(7, 0) // 7am every day
val LocalTime evening = new LocalTime(20, 0) // 20pm every day
if (now.toLocalTime().isAfter(morning) && now.toLocalTime().isBefore(evening)) {
sendCommand(anotheritem, "ON")
}
end
Now I will execute the rule only if the local time is between evening and morning from the next day, like this
rule ButtonTimeOfNight
when
Item myitem received command
then
val LocalTime evening = new LocalTime(20, 0) // 20pm every day
val LocalTime morning = new LocalTime(7, 0) // 7am every day
if (now.toLocalTime().isAfter(evening) && now.toLocalTime().isBefore(morning)) {
sendCommand(anotheritem, "ON")
}
end
Typically I recommend implementing something like [Deprecated] Design Pattern: Time Of Day to centralize this time of day logic so it can be implemented once and reused in all of your rules.
That out of the way the problem you have is LocalTime gives you the time at 20:00 and 07:00 today. It will never be the case where a time is both after 20:00 and before 07:00 on the same day.
I think the toLocalTime is redundant and not needed as it gives you local time anyway so:
if(now.getHours > 20 || now.getHours <=7)
Another alternative approach would be
val evening = now.withTimeAtStartOfDay.plusHours(20) // 20 pm today
val morning = now.withTimeAtStartOfDay.plusHours(31) // 7 am the next day
if(now.isAfter(evening) && now.isBefore(morning)) {