Timex.from_now() How to update liveview every second or more optimized way, to display x seconds ago?

Timex’s from_now gives the relative duration from now. But I’d like to show it in real time.
The x seconds ago would count up every second. The minutes every minute, and so on.

Is there a better way to do this than just update the view every second?

 <div class="text-xs font-normal">{Timex.from_now(time)}</div>
"2 seconds ago"

Just use Javascript. There’s no need to do this on the server.

<div id="time-div" data-time={Timex.from_now(time)}>&nbsp;</div>
<script>
  const div = document.querySelector("#time-div");
  const startTime = new Date(div.dataset.time);

  function updateTime() {
    const now = new Date();
    const diff = Math.floor((now - startTime) / 1000);
    div.textContent = new Date(now).toLocaleString();
  }

  setInterval(updateTime, 1000);
  updateTime();
</script>
2 Likes

My preferred approach to display relative times or localize timestamps accordingly to the user browser preferences is to use the relative-time-element web-component.

You just need to:

<relative-time datetime={time} />
1 Like