Subtracting 2 hours from datetime item

Hello,

I have a DateTime item coming in from the ical binding showing me when something is going to happen from my calendar. I’m trying to take that item, subtract 2 hours from that and set that as a new dateitem’s value.

I’m trying to it is like this:


Calendar_Next_Event_Start_2Hour_Warning.postUpdate(Calendar_Next_Event_Start.minusHours(2))

This gives the following error:

2024-06-05 18:09:39.235 [ERROR] [internal.handler.ScriptActionHandler] - Script execution of rule with UID '8507d63e20' failed: Calendar_Next_Event_Start_2Hour_Warning.postUpdate(Calendar_Next_Event_Start. ___ minusHours(2))
   The method minusHours(int) is undefined for the type DateTimeItem; line 1, column 109, length 10

Any thoughts on how this can be done? I plan to use this new datetime item as a trigger on a rule.

Rules DSL

Calendar_Next_Event_Start_2Hour_Warning.postUpdate((Calendar_Next_Event_Start.state as DateTimeType).zonedDateTime.minusHours(2).toString())

In jruby

Calendar_Next_Event_Start_2Hour_Warning.update(Calendar_Next_Event_Start.state - 2.hours)
1 Like

@jimtng - Thanks for the quick reply! This works perfectly.

I had made some progress on this but was still missing the final .toString() bit. Appreciate the help!

For completeness here’s Blockly:

and JS Scripting

items.Calendar_Next_Event_Start_2Hour_Warning.update(time.toZDT(items.Calendar_Next_Event_start).minusHours(2));
1 Like

As a followup, if I want to take my newly created 2 hour warning item and use it as a time based trigger for another rule, will this work since it is a string type item?

If it’s a String Item then no, that won’t work. But why is it a String Item? It should be a DateTime Item. The String version of the DateTime passed as an update to the Item will get parsed into a DateTime, if it’s being sent to a DateTime Item and is parsable.

the need to call toString is really just a quirk of Rules DSL and is a way to work around it’s flakey typing system. You’ll notice that the call to toString isn’t there for any of the other languages.

Thanks @rlkoshak,

I think I made an error when I first created my new item and created it as a string item. I changed it to a datetime item and reran my rule and all is now set. Appreciate the explanation!

@rlkoshak would it be useful if we added an offset option to the DateTimeTrigger?

Yes! There is already an issue open to add that. Allow offset for "at the time specified in an item's state" trigger · Issue #4195 · openhab/openhab-core · GitHub

As far as I know no one has taken it upon themselves to add it but there is definitely interest and I think it would be an excellent feature.

1 Like

I have no idea how big of a use case this would fill, but I have two rules I want to use it for.

Thanks @jimtng!

https://github.com/openhab/openhab-core/pull/4271

1 Like

FYI This appears to be broken in 5.0.1 using rules DSL