The link posted by @chrismast has a number of valid approaches but I find it to be easier to use Duration
.
Without persistence
import java.time.Duration
var ZonedDateTime lastOffTime = null
rule “Rele1”
when
Item GenericMQTTThing_n1 changed
then
if(newState == OFF) {
lastOffTime = now
}
else if(lastOffTime !== null){
var diff = Duration.between(lastOffTime, now)
...
}
end
See Duration (Java SE 11 & JDK 11 ) for all the capabilities of Duration. By default diff.toString()
will output the duration in DD:HH:MM format (assuming the duration is more than 24 hours long). You could also get at the total number of minutes with diff.toMinutes()
or just the minutes remaining after getting the hours diff.toMinutesPart()
.
I find the code using Duration
to be shorter and far easier to understand.