Elixir converting datetime to string
Asked Answered
K

2

6

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

If I put the return value I get a complain:

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

If I try to transform it to string using 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 skip the from_erl part:

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

I get:

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

Kimbro answered 21/3, 2017 at 22:34 Comment(0)
E
5

To obtain a standard erlang datetime value need to remove 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\""
Efflorescent answered 21/3, 2017 at 22:56 Comment(1)
wasn't going to find this anytime soonKimbro
P
2

Per the Ecto 3.0 changelog, Ecto.DateTime no longer exists. In the cases where you do not have timezone information available, you can use NaiveDateTime.from_erl() as a replacement for Ecto.DateTime.from_erl()

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

Plossl answered 3/4, 2019 at 19:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.