rschooley
How do I store a Unix timestamp in Ecto?
I have a timestamp coming back from a 3rd party package. I have read these articles and don’t see how to just store this value in my db and have it come back as some sort of date type in elixir.
https://hexdocs.pm/ecto/Ecto.Schema.html
- is there an Ecto type that should just take in the timestamp and convert it?
- do I need to convert it manually in the changeset? (that would seem strange)
The codes:
##My Timestamp##
DateTime.from_unix 1518960668
Yeah this is cool
##using :utc_datetime##
** (FunctionClauseError) no function clause matching in Ecto.Type.cast_naive_datetime/1
The following arguments were given to Ecto.Type.cast_naive_datetime/1:
# 1
1518960668
Attempted function clauses (showing 4 out of 4):
defp cast_naive_datetime(binary) when is_binary(binary)
defp cast_naive_datetime(%{"year" => empty, "month" => empty, "day" => empty, "hour" => empty, "minute" => empty}) when empty === nil or empty === ""
defp cast_naive_datetime(%{year: empty, month: empty, day: empty, hour: empty, minute: empty}) when empty === nil or empty === ""
defp cast_naive_datetime(%{} = map)
code: token = token_fixture()
##using :time##
changeset errors:
...
errors: [expires_at: {"is invalid", [type: :time, validation: :cast]}]
Most Liked
rschooley
OK, I have both versions working, and will paste here in case someone else has this same issue.
Short of it, cast does work:
defmodule UnixTimestamp do
@behaviour Ecto.Type
def type, do: :naive_datetime
def cast(timestamp) when is_integer(timestamp) do
case DateTime.from_unix(timestamp) do
{:ok, date} -> {:ok, DateTime.to_naive(date)}
{:error, reason} -> {:error, reason}
end
end
def cast(_), do: :error
def dump(value), do: Ecto.Type.dump(:naive_datetime, value)
def load(value), do: Ecto.Type.load(:naive_datetime, value)
end
and my migration uses naive_datetime so the field is like the timestamps.
Source:
At the bottomish of the second article it has an example of implementing the type.
OvermindDL1
For making your own type it’s documented at:
https://hexdocs.pm/ecto/Ecto.Type.html
Specifically:
https://hexdocs.pm/ecto/Ecto.Type.html#c:dump/1
https://hexdocs.pm/ecto/Ecto.Type.html#c:load/1









