Format datetime item as elapsed time?

  • Platform information:
    • Hardware: RPi3
    • OS: OpenHABian
    • Java Runtime Environment: OpenJDK Runtime Environment Zulu11.45+27-CA (default)
    • openHAB version: 3.1.0 (stable)

I’m wondering if anybody has found an efficient way to format datetime Items as “time elapsed”?

In my setup I’ve created a virtual item for every device called [devicename]_last_report and used the “Timestamp on change” profile for all of the device’s active channels, so that I can detect devices which have stopped responding for whatever reason. There are a few other nuances in how I’ve set it up but it works great, and I use the Java formatter to make nice-looking dates in the OH3 UI.

The last tweak I’d like to make is to change the format of the datetime Items to something like “5 days ago”. I believe I could set up a rule (like this) to update a second Item with this info as a string, but is it possible to calculate this on a datetime Item directly using state descriptions?

Thanks!

If you just want to display this time elapsed somewhere in the MainUI then you don’t need to do anything else with items or rules, this ability is available directly in the UI via the dayjs library with the fromNow() method.

The following widget code:

component: f7-card
config:
  title: Front Door
  footer: =dayjs(items["Door_FrontDoor_Status_TS"].state).fromNow()
  content: =items["Door_FrontDoor_Status_TS"].state

Shows both the unaltered datetime timestamp and the human readable elapsed time version with dayjs:
image

This is available in a custom widget or any of the widget that you manually add to the overview page. If you want to have this be what you see as the default view for certain items then you will have to build your own custom widget that uses dayjs and then set that widget as the default standalone or default list widget for that item.

3 Likes

Yes!! This is exactly what I was looking for. Thank you so much, it works perfectly.