Problem with jodatime within rules

Hi,

I’m really struggling to use ‘now’ in OH2 - I was managing fine in OH1. See the below snippet:

var DateTime daystart = Sunrise.state 
logInfo("test1", "sunrise = " + Sunrise.toString)
    
var DateTime dayend = Sunset.state 
logInfo("test2", "sunrise = " + Sunset.toString)
    
val boolean isdark = daystart.afterNow || dayend.beforeNow
logInfo("test3", "isdark = " + isdark)

If this runs in a rule, the output is:

2015-11-11 21:25:15 [INFO ] [e.smarthome.model.script.test1:48   ] - sunrise = Sunrise (Type=DateTimeItem, State=2015-11-11T07:30:00, Label=Sunrise, Category=null)
2015-11-11 21:25:15 [INFO ] [e.smarthome.model.script.test2:48   ] - sunrise = Sunset (Type=DateTimeItem, State=2015-11-11T16:09:00, Label=Sunset, Category=null)
2015-11-11 21:25:15 [ERROR] [.s.m.s.e.ScriptExecutionThread:48   ] - Error during the execution of rule 'Landing Motion Detected': The name '<XFeatureCallImplCustom>.afterNow' cannot be resolved to an item or type.

So tests 1 & 2 work, but we fail before test3 completes. Please don’t judge me on the use of afterNow or beforeNow - I’ve tried a lot of things and that’s the latest unsuccessful attempt. Has the use of ‘now’ changed in OH2? Am I just using wrong types? Can someone make the line work? After that I can apply it to all of the rest of my rules.

Cheers,
Dan

Are you sure that this code works on openHAB 1?
Already the line

var DateTime daystart = Sunrise.state

looks very wrong to me. “Sunrise.state” is of an openHAB type, i.e. DateTimeType, but not org.joda.time.DateTime. In fact, there is no dependency from openHAB types to Joda at all.

What does it output if you change the second line to

logInfo(“test1”, "sunrise = " + daystart)

?

Hi Kai, thanks for the response. I’m sorry I’ve taken so long to respond - I’ve had sunrise and sunset defined via cron in the meantime.

I didn’t realise that I was confusing DateTimeType with the joda DateTime. I’ve gone back to the start and have the following code working:

var DateTime daystart = new DateTime((Sunrise.state as DateTimeType).calendar.timeInMillis)
var DateTime dayend = new DateTime((Sunset.state as DateTimeType).calendar.timeInMillis)
val boolean isdark = daystart.afterNow || dayend.beforeNow
logInfo("test1", "sunrise = " + daystart)
logInfo("test2", "sunset = " + dayend)
logInfo("test3", "isdark = " + isdark)

with output:

2015-12-29 16:09:00 [INFO ] [e.smarthome.model.script.test2:48   ] - sunrise = 2015-12-29T08:37:00.000Z
2015-12-29 16:09:00 [INFO ] [e.smarthome.model.script.test2:48   ] - sunset = 2015-12-29T15:47:00.000Z
2015-12-29 16:09:00 [INFO ] [e.smarthome.model.script.test3:48   ] - isdark = true

I sincerely apologise for taking up your time with this one. Hopefully the working snippet will help anyone else who comes across the same issue.

Cheer,
Dan

2 Likes