OH 4 -> How to add or subtract hours and minute from DateTime item?

A problem seems to be that if next_outbound_begin is “UNDEF”, the code throws an error.

I had this:

var aantalminuten = 4
var lastseenstring = items["Camera_tuin_en_terras_G5_Bullet_Last_Seen"].state
var lastseendate = new Date (lastseenstring)
var aantalminutengeledendate = new Date(new Date - (aantalminuten * 1000 * 60))

if (aantalminutengeledendate < lastseendate || lastseendate == "Invalid Date") {
  console.log("do something")
}

This worked. But for time.toZDT, I had to find a workaround like this:

var aantalminuten = 4
var aantalminutengeleden = time.toZDT(-aantalminuten * 1000 * 60)
var lastseenstring = items["Camera_tuin_en_terras_G5_Bullet_Last_Seen"].state

try {
  var lastseen = time.toZDT(lastseenstring)
  if (lastseen.isBefore(aantalminutengeleden)) {
    var meldingnoodzakelijk = true
  } else {
    var meldingnoodzakelijk = false
  }
} catch {
  var meldingnoodzakelijk = true
}

if (meldingnoodzakelijk) {
  console.log("do something")
}

I’m sure there is a more elegant solution? :slight_smile:

You still have to test whether the data is valid or not. The only difference is that you need to do the test before you try to convert it to a ZonedDateTime, not after like in your existing code.

var lastseenitem = items["Camera_tuin_en_terras_G5_Bullet_Last_Seen"]
if(lastseenitem.isUninitialized || time.toZDT(lastseenitem).isBefore(time.toZDT('PT-4M'))) {
    console.log("do something");
}

This is how I would implement it. The trick is you have to test for NULL/UNDEF before trying to convert the Item to a ZonedDateTime. Then the code pretty much exactly mirrors your original only with less code overall and no exception is thrown.

I’m using an ISO8601 Duration String for -4 minutes instead of calculating the milliseconds.

1 Like

I didn’t know how.

Thanks. I’ll try to use that ISO8601 format, that’s probably good practice. :slight_smile:

You can also test for NULL and UNDEF with if(items.MyItem.state == "NULL" || items.MyItem.state == "UNDEF") but using isUninitialized is shorter. But there may be cases where you want to only test for one or the other and not both.

Does this .toZDT also work in some way with setTimeout? Or does that parameter have to be calculated as (minutes * 60 * 1000)?

setTimeout requires the number of milliseconds so yes, you’d have to do the calculation.

However, openhab-js adds a getMillisFromNow() to ZonedDateTime so you can do all the math using ZDTs and then extract the milliseconds when creating a timer using setTimeout or setInterval.