Motion detection timer rule

Hi Guys,

i´m struggling with a rule here.
I would love to get some help of you.
For the Setup:
I got a Motion Detector and a light switch, both are working.
so my problem is i want that the rule only triggers betwenn 06:00am - 08:00am and 07:00pm-02:00am. the rest of the day it should be off.

i got this so far:
rule “Motion Sensor Lights On”
when
Item HCSR501_2 changed from 0 to 1
then
if(now.getHourOfDay > 6 && now.getHourOfDay < 8 && now.getHourOfDay > 19 && now.getHourOfDay < 2){
Switch2.sendCommand(ON)
}
end

rule “Motion Sensor Lights Off”
when
Item HCSR501_2 changed from 1 to 0
then
if(now.getHourOfDay > 6 && now.getHourOfDay < 8 && now.getHourOfDay > 19 && now.getHourOfDay < 2){
Switch2.sendCommand(OFF)
}
end

for me this seems to be right but it doesn´t work. does anybody know why and whats wrong?
thanks alot for your help guys!!
greets
mike

at first, please put Code in Code fences (one of the Icons on the right) - makes it more readable.

then to your code. As you defined your if-clause, it will never be true - and therefore the Switch never turns on. Why?
You defined all conditions as && - meaning AND. So, now.getHourOfDay will never be true for >6 AND <8 AND > 19 AND < 2. What you’d like to do is add some || - meaning OR and put both (morning and evening in a logical boundary):

if ( (now.getHourOfDay > 6 && now.getHourOfDay < 8) || (now.getHourOfDay > 19 && now.getHourOfDay < 2) ){

So - I’m not sure, if this one works, as >19 AND <2 probably contradict each other. You could either add a third boundary (the lazy solution)

if ( (now.getHourOfDay > 6 && now.getHourOfDay < 8) || (now.getHourOfDay > 19 && now.getHourOfDay <= 23)  || (now.getHourOfDay >= 0 && now.getHourOfDay < 2) ){

or you could use some of the “time of the day”-pattern explained here (pro version):

@binderth ok next time i use the code fence sorry.

thanks for your help here i got it to work and will check out the time of day pattern aswell, thanks again man!!!
have a great day!!
greets
mike

1 Like