People are confusing you becaues they do not understand that custom button card uses different templating.
{{ ... }}
signifies a jinja template, only useable in the configuration of home assistant.
[[[ ... ]]]
is a JS template. The syntax is completely different than jinja and the solutions here will not work.
jazzyisj’s solution will work if you create a template sensor, like he suggests.
Everything vingerha has said will not work because of the reason I highlighted above.
The simplest template that will work (only on times that are in the past) is to make a template sensor and display that value:
template:
- sensor:
- name: 'Server Uptime'
unique_id: server_uptime
icon: mdi:clock-start
state: >
{% set t = now() %}
{{ states('sensor.jarek_activewindow') | as_datetime | as_local | relative_time }}
You have to include now()
in your template even though you aren’t using it to ensure that the sensor updates once a minute.
If you want this to update once a second, you have to tailor it a bit differently.
template:
- trigger:
- platform: time_pattern
seconds: /1
sensor:
- name: 'Server Uptime'
unique_id: server_uptime
icon: mdi:clock-start
state: >
{{ states('sensor.jarek_activewindow') | as_datetime | as_local | relative_time }}
If you want to do this calculation in the custom button card, you’ll have to build the syntax yourself and add an item to the card to force updates on an interval. You’ll have to adjust it because it’s written in english.
label: |
[[[
entity_id = (entity === undefined) ? 'Invalid Entity' : entity.entity_id;
var statestr = (entity === undefined || entity.state === undefined) ? null : entity.state;
var date = (statestr && entity.attributes.device_class === 'timestamp') ? new Date(statestr) : null;
if (date){
let now = new Date();
var tdelta = Math.floor((now - date)/1000);
// console.log(`${entity_id}: ${tdelta}`);
function plural(one, more_than_one, divisor){
var ret = Math.floor(tdelta/divisor);
return (ret == 1) ? `${ret} ${one} ago` : `${ret} ${more_than_one} ago`;
}
var value;
if (tdelta < 60)
value = plural('second', 'seconds', 1);
else if (tdelta < 60 * 60)
value = plural('minute', 'minutes', 60);
else if (tdelta < 60 * 60 * 24)
value = plural('hour', 'hours', 60 * 60);
else if (tdelta < 7 * 60 * 60 * 24)
value = plural('day', 'days', 60 * 60 * 24);
else
value = plural('week', 'weeks', 7 * 60 * 60 * 24);
return value;
} else {
return "Unknown";
}
]]]