Hour and minute in a rule

I use this rule(example) to do certain things like automating lights only at certain hours…

rule "example"
when
Item motion changed to ON
then
val Integer currentHour = now.getHour()
if ((8..19).contains(currentHour)){
bedroom.sendCommand(ON)
 }
end

so i turn on the light only between 8am and 8 pm,but what if i want to turn it on between 8:30am and 8:45pm ?Can anyone give me an example to work with?

Add a virtual item and a rule with cron triggers to turn the virtual item on or off. Then your rule above just needs to check if the virtual item is on/off before firing the command.

It’s a little more indirect, but gives you more flexibility, since you can have multiple periods (e.g. 8:30am-10am and 7pm-8:45pm) and other triggers that aren’t based on time.

or instead of using time you could use the astro binding to have the light on only when it is dark.

To add to @rpwong Create a new switch item named like enable_lights

Then you can have a rule that runs on a cron trigger Time cron "0 30 8 ? * * *" 8:30am

rule "Enable Lights"
when
  Time cron "0 30 8 ? * * *"  or astro binding trigger
then
  enable_lights.sendCommand(ON)
end

rule "Disable Lights"
when
Cron trigger or astro binding trigger
then
  enable_lights.sendCommand(OFF)
end


rule "Motion detected turn light on if lights enabled "
when
Item motion changed to ON
then

if (enable_lights.state == ON){
bedroom.sendCommand(ON)
 }
end

i already use astro and iluminance readings from my aqara motion sensors to determin darkness night time for a more generic trigger.I just want to find out if there is a way to get hour and minutes in 2 values and use them for more detailed periods of time within the day…

You can. Work in minutes instead of hours. Set a variable to now and get the minutes and hours, multiply the hours by 60 and add to the minutes. Then do your compare in minutes.

Many people use datetime objects within their rules, allowing use of isAfter and isBefore methods.
See “Time of day” postings.

1 Like

In JRuby:

rule 'example' do
  changed MotionItem, to: ON
  between '8:30am'..'8:45pm'
  run { BedRoomItem.on }
end
1 Like