We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
Show relative time like GitHub
almirsarajcic
Created
Yesterday, I wrote about using Timex to display relative time (https://elixirdrops.net/d/dkwi9Whb). While looking at how GitHub handles this, I discovered they have open-sourced their approach.
For this to work, you’ll need to install the @github/relative-time-element
npm package.
If you are wondering how to use npm packages with Phoenix, I have written about that, too: https://elixirdrops.net/d/7paEUio9.
Then use it in your HEEX:
def created_at(assigns) do
~H"""
<relative-time datetime={"#{@created_at}+00:00"}></relative-time>
"""
end
It will create an element in the DOM similar to this:
<relative-time datetime="2024-12-19 08:59:23+00:00" title="Dec 19, 2024 at 9:59 AM GMT+1"></relative-time>
which will display the correct relative time in your browser and will update as you stay on the page.
However, it’s not going to display anything if JS is disabled.
To provide the best of both worlds, you can combine this with the Timex solution:
def created_at(assigns) do
~H"""
<relative-time datetime={"#{@created_at}+00:00"}>
<%= Timex.format!(@created_at, "{relative}", :relative) %>
</relative-time>
"""
end
It’s going to work regardless of whether JS is enabled or not. Updating the string will not happen if it’s disabled, though.
If I had a choice, I would avoid Timex completely as it’s a huge dependency and simply use the NaiveDateTime.to_string/1
as a backup if JS is disabled.
def created_at(assigns) do
~H"""
<relative-time datetime={"#{@created_at}+00:00"}>
<%= @created_at %>
</relative-time>
"""
end
Copy link
copied to clipboard