"Beautify" inserted_at

I would like to create a view function helper which I can later use in my templates to beautify the inserted_at dates.

2016-12-23 15:03:51 is not that pleasant to read, so I was thinking of having something similar to 2016 / Dec / 23 or 2016 / 12 / 23.

I could find any kind of documentation, or I might’ve missed it, which would show how to put this into action.
Any suggestions?

Your inserted_at column is likely an Ecto.DateTime or a NaiveDateTime struct. In both cases, you can match on the fields and build the formatting function that you want:

def beautiful_date(%{year: year, month: ..., ...}) do
  "#{year}-#{month}..."
end

If you are not sure about the keys, you can use something like Map.keys(datetime) to get the available keys to match on.

You can also use third party libraries, such as Timex and Calecto, that include functions to help with formatting too.

1 Like

You could use, for example, Timex:

iex(3)> Timex.format(user.inserted_at, "{YYYY} / {M} / {D}") 
{:ok, "2016 / 7 / 25"}
iex(4)> Timex.format(user.inserted_at, "{YYYY} / {Mshort} / {D}")
{:ok, "2016 / Jul / 25"}

See the documentation for more details…

If you don’t already use Timex, and want to avoid adding a new dependency, it’s easy to roll your own:

2 Likes

Thanks!
I didn’t imagine it would be that easy… I implemented markdown fairly easily, but I thought that it might be a bit more difficult with timestamps.

Elixir amazes me once again.

@jwarlander I didn’t even see that SO result on my Google search.