Formatting a time in Elixir

Gordon Isnor picture Gordon Isnor · Aug 11, 2015 · Viewed 7.7k times · Source

I'm new to Elixir, trying to port a Rails API to Phoenix as a learning project.

I have a Postgres time field, which I've added to an Ecto scheme:

field :start_time, Ecto.Time

Problem: I'd like to output a 12-hour formatted version of a time such as 16:30 as a string: 4:30pm, for example. I have been having trouble finding an easy/standard way of doing this.

This is the closest I've yet come to a solution:

def format_time(time) do
  {:ok, {hours,minutes,y, z}} = Ecto.Time.dump(time)
  {hour, ampm} = Timex.Time.to_12hour_clock(hours)
  "#{hour}:#{minutes}#{ampm}"
end

This seems like a ridiculous and ridiculously long piece of code for something I imagine already has a more concise and standard implementation; in addition it has the problem of outputting 2:0pm instead of 2:00 pm – formatting the 0 with a trailing zero was additionally long and complicated piece of code that I was working on –– at which point I started feeling like things were going way off track.

Advice appreciated!

Answer

Paweł Obrok picture Paweł Obrok · Aug 11, 2015

You can use the formatting facilities of timex since you're already using that, but first you need to change your Ecto.Time into a Timex.DateTime that can be formatted with those.

use Timex

{{0, 0, 0}, Ecto.Time.to_erl(time)}
|> Timex.Date.from
|> DateFormat.format!("{h12}:{0m} {am}")