As I said above and @ErikDB said, this code is JS code. You do not put JS code into a .rules file. See JavaScript Scripting - Automation | openHAB for everything you need to know to write JS rules.
Working with epoch and JS’s Date
class is arcane, error prone, and unnecessarily long and involved.
JS Scripting’s helper lkibrary (i.e. openhab-js) includes the entirety of the joda-jd library which is made available in the time
name space (e.g. time.ZonedDateTime
). In addition, there is a helper method called time.toZDT()
which converts almost anything that can be converted into a time.ZonedDateTime
. You never really need to call new
to get a ZonedDateTime
, just use time.toZDT()
.
For example:
Code |
What you get |
time.toZDT() |
now |
time.toZDT(items.MyDateTimeItem) |
the state of the Item as a ZonedDateTime |
time.toZDT(6000) |
now plus six seconds |
time.toZDT('PT5H2M') |
now plus five hours two minutes |
time.toZDT('08:00') |
today at 08:00 |
time.toZDT('9:00 pm') |
today at 21:00 |
There’s more, these are just some of the ones I use more often.
Once you have a ZonedDateTime
you have all the plusMinutes and minusSeconds type methods. The time.Duration
class can determine the difference between two ZonedDateTimes.
See JavaScript Scripting - Automation | openHAB for details.
All the calls to openHAB’s API (createTimer
, postUpdate
, sendCommand
, executeCommandLine
, etc.) exepects a time.ZonedDateTime
or time.Duration
.
So, instead of the five lines of code required to add 90 minutes to the current state of a DateTime Item:
var minutestosubstract = 90
var timetosubstractfromstring = items["next_outbound_begin"].state
var timetosubstractfrom = new Date (timetosubstractfromstring)
var ETD = new Date(timetosubstractfrom.getTime() - (minutestosubstract * 60 * 1000))
items["ETD_item"].sendCommand(ETD)
we have two
var ETD = time.toZDT(items["next_outbound_begin"]).minusMinutes(90);
items["ETD_item"].sendCommand(ETD);
And those two lines of code requires less mental gymnastics to understand (e.g. .minusMinutes(90)
as opposed to - (minutestosubteract * 60 * 1000)
).
Since using the time.*
classes are going to be required anyway some of the time and using them results in shorter and easier to understand code, using them in most circumstances is better than using the native JS Date
class with is far less capable and requires a lot more effort to work with. And it’s going to be converted to a ZonedDateTime for you anyway before it can be used in that sendCommand.