Elixir converts date and time to string

I have a raw sql query that returns a datetime field and I want to return json with these results.

If I supply the return value, I get a complaint:

(Poison.EncodeError) unable to encode value: {{2017, 3, 21}, {0, 0, 0, 0}}

If I try to convert it to a string with Timex

:

Timex.format!(Ecto.DateTime.from_erl(datetime_field), "%Y-%m-%d %H:%M:%S", :strftime)

I get:

** (FunctionClauseError) no function clause matching in Ecto.DateTime.from_erl/1

If I miss a part from_erl

:

Timex.format!(datetime_field, "%Y-%m-%d %H:%M:%S", :strftime)

I get:

** (Poison.EncodeError) unable to encode value: {:error, :invalid_date}

+4


source to share


2 answers


To get the standard erlang

datetime value , you need to remove the fourth value (microseconds) from the second tuple:



datetime = {{2017, 3, 21}, {0, 0, 0, 0}}
{{year, month, day}, {hours, minutes, seconds, _}} = datetime
datetime = {{year, month, day}, {hours, minutes, seconds}}
Poison.encode! Ecto.DateTime.from_erl(datetime)
#=> "\"2017-03-21T00:00:00\""

      

+5


source


As of 3.0 Ecto.DateTime

changes Ecto.DateTime

, Ecto.DateTime

no longer exists. In cases where you do not have available time zone information, you can use NaiveDateTime.from_erl()

insteadEcto.DateTime.from_erl()



If you need more formatting beyond the basic iso8601 or to_string stuff you need to look at https://hexdocs.pm/timex/Timex.html#format/2

0


source







All Articles