Convert from DateTime item in JavaScript

I need to set the timeout on a timer that takes milliseconds.
I have a DateTime item.
I need to convert that to epoch milliseconds, then subtract from epoch now, and set the timer with that time delta.
This is JavaScript ECMAv11 using the rules editor.

I am unable to find documentation that describes how to get the epoch from a DateTime item.

You don’t need to do all of that. There’s a millisFromNow() method on ZonedDateTime and time,toZDT() will convert the DateTime Item or the rawState to a ZonedDateTime.

var delay = time.toZDT(items.getItem("MyDT")).millisFromNow();

or

var delay  = time.toZDT(items.getItem("MyDT").rawState).millisFromNow();

However, in all cases, as documented, an Item’s .state always returns the String representation of the state. And also as documented, the library can’t process the toString if it includes the timezone.

After the latest update (4.0.3, JavaScript), I get from lines like

var alarm=time.toZDT(items.getItem("nextalarm")

the following error message
Error: “nextalarm (Type=DateTimeItem, State=2023-10-05T07:15:00.000+0200, Label=Nächster Alarm, Category=time)” is an unsupported type for conversion to time.ZonedDateTime

Am I missing something here?

items.getItem("nextalarm").getState().getZonedDateTime() disclaimer I’m not familiar with jsscripting

See OH 4.0.3: Rules (JS Scripting) throws error with "time.toZDT": unsupported type for conversion to time.ZonedDateTime

It’s a known bug that has been fixed but not backported.

time.toZDT(items.nextalarm) will normally work except for that bug.

The work around is time.toZDT(items.nextalarm.state) or upgrading openhab-js to a version with the fix. time.toZDT(items.nextalarm.rawState) should also work as a work around.

In order to get at the ZonedDateTime as you attempted it would be items.nextalarm.rawState.getZonedDateTime().

Dear all,
Thank you for your helpful responses.
I can confirm that calling the state property instead of the item works.
It seemed the most simple workaround at this time.
Thanks again

1 Like