water
September 14, 2025, 8:24pm
1
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)}> </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>
Wigny
September 15, 2025, 9:31pm
3
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} />
water
September 20, 2025, 7:59pm
4
<div class="text-xs font-normal">
{time
|> DateTime.shift_zone!("Europe/London")
|> Calendar.strftime("%d %B %H:%M",
month_names: fn month ->
{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}
|> elem(month - 1)
end
)} - 
<relative-time
datetime={time}
format="elapsed"
threshold="PT60M"
formatStyle="narrow"
/> AGO
</div>
20 Sep 19:35 - 22m 27s AGO
If you want to do it on the server, I describe a way of doing it here:
Motivation:
I want to write
<.relative_datetime timestamp={my_schema.inserted_at} />
and to get this in my browser:
[en]
while other users get, say, this (Arabic) in their browser:
[ar]
I wanted to render a NaiveDateTime as something like “30 seconds ago”. I wanted it to live-update. I wanted to use the user’s chosen locale.
Normally I would “live update” something like this on the client side but I wanted to use Cldr locale features for easy translating.
Turning a DateTime into a nice …