# Show relative time like GitHub

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:

```elixir
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:

```html
<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:
```elixir
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.
```elixir
def created_at(assigns) do
  ~H"""
  <relative-time datetime={"#{@created_at}+00:00"}>
    <%= @created_at %>
  </relative-time>
  """
end
```


---

Created by: almirsarajcic
Date: December 19, 2024
URL: https://elixirdrops.net/d/iTobNHP9
