Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting a time in Elixir

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!

like image 333
Gordon Isnor Avatar asked Aug 11 '15 13:08

Gordon Isnor


4 Answers

I had the same problem and using a library like Timex. That's my way how to handle dates. I don't know if there better work cases.

  • Calendar for parsing and some functions.
  • Calecto for using Calendar with Ecto

In this case you can use Calendar.Strftime for a formatted date/time string.

I hope it helps.

like image 167
Fabi755 Avatar answered Nov 20 '22 13:11

Fabi755


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}")
like image 21
Paweł Obrok Avatar answered Nov 20 '22 12:11

Paweł Obrok


You're using Timex, but not its format! method which allows for easy time and date formatting.

https://david.padilla.cc/posts/19-date-formatting-in-phoenix-elixir is a good write up on using Timex.

It looks like you might be able to do something like the following:

Timex.DateFormat.format!(time, "%H:%M%P", :strftime)

See https://github.com/bitwalker/timex/blob/master/lib/format/datetime/formatters/strftime.ex for the full list of formatting options.

like image 6
sevenseacat Avatar answered Nov 20 '22 13:11

sevenseacat


A simple way to do it is to use strftime string formatting available in Calendar. Using Calecto you can even use the basic types such as Ecto.Time or Ecto.DateTime. This can be piped directly to Calendar's formatting, like so:

@ecto_struct.some_time |> Calendar.Strftime.strftime! "%I:%M%P"

Will result in:

"02:30pm"

All you have to do is add Calecto as a dependency:

defp deps do
  [ {:calecto, "~> 0.4.1"}, ]
end
like image 1
Lau Avatar answered Nov 20 '22 11:11

Lau