Time between x and y to do something

Hi

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

But it doesn’t work…

How could I solve this problem

Where because that is an unusual approach.

Typically I recommend implementing something like 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.

You will want to do something closer to:

if(now.toLocalTime.getHours > 20 || now.toLocalTime.getHours <= 7)

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)) {
1 Like

Thank you for the Quick answer. I’ll try it tomorrow.
Can I Simply implement the Code or should i do something more (Binding, Import… etc.)