Difference between 2 timestamps

  • Platform information:
    • Hardware: ARM71, Raspberry Pi3
      openHAB version: 3

Hello! Need help in rule
I have a rele, and i need calculate the difference between two states - From ON to OFF in h:m:s.
How can i do?

Thanks

rule “Rele1”
when
Item GenericMQTTThing_n1 changed
then

end

Try this.

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.

1 Like

Thanks a lot! I have done and it works! Thanks

This is so good, just what I needed too, thanks!