relative_time is a jinja2 function, which means it isn’t available from the JS frontend. This is not the exact same use case, but it could be possible to use raw JS (although I haven’t managed to get the state to update once a minute yet). Refreshing the dashboard shows the right duration at least:
- type: 'custom:button-card'
entity: switch.biltak_motorvarmare
name: Motorvärmare
icon: 'mdi:car'
show_state: true
state_display: |
[[[
if (entity.state === 'on') {
function humanReadableDuration(duration) {
var hours = Math.floor(duration / 1000 / 60 / 60);
var minutes = Math.floor((duration / 1000 / 60 / 60 - hours) * 60);
var result = '';
if (hours > 0) {
result += hours + ' h ';
}
return result + minutes + ' min';
}
var timeDiff = new Date().getTime() - new Date(entity.last_changed).getTime();
return 'Stäng av (på i ' + humanReadableDuration(Math.abs(timeDiff)) + ')';
}
else
return 'Lägg på';
]]]
If I’d need to mimic Jinja2’s relative_time() I’d use JS’s moment().fromNow() function, but it’s not implemented in custom:button-card.
And since this ultra-useful card isn’t maintained anymore, there’s no chance the moment() will get added.
Is there any other way to come by this?
(I fear expanding @slovdahl’s post to capture days, weeks, months and even years might be quite a heavy load for older devices displaying the frontend? At least in cards still using triggers_update: all.)