0
votes

I have a DateTime in this format:

{{2017, 2, 2}, {14, 43, 50, 0}}

I want to convert it to "2 Feb 2017" or "2 February 2017" or "2/02/2017" without using Timex or any other dependency except, if needed, Ecto.DateTime. How can I do that?

2

2 Answers

0
votes

Using Ecto.DateTime

{{2017, 2, 2}, {14, 43, 50, 0}}
|> Ecto.DateTime.cast!
|> Ecto.DateTime.to_date
|> Ecto.Date.to_string

# => "2017-02-02"

Using Elixir.Date

{date, _time} = {{2017, 2, 2}, {14, 43, 50, 0}}

date
|> Date.from_erl!
|> Date.to_string

# => "2017-02-02"

Further Modification:

"2017-02-02"
|> String.split("-")
|> Enum.reverse
|> Enum.join("/")

# => "02/02/2017"

For a simple case, these might work - but I seriously recommend using Timex for more complicated ones. See this answer for reference.

0
votes

For String Months

defmodule MyDate do
  @months ~w(January February March April May June July August September October November December)

  def to_string({{y, m, d}, _time} = datetime) do
    "#{d} #{Enum.at(@months, m - 1)} #{y}"
  end
end

Usage:

MyDate.to_string({{2017, 2, 2}, {14, 43, 50, 0}})
# => "2 February 2017"

For a simple case, this might work - but I seriously recommend using Timex for more complicated ones. See this answer for reference.