bitwalker / timex_ecto

An adapter for using Timex DateTimes with Ecto
MIT License
162 stars 68 forks source link

Rendering JSON in Phoenix w/ Timex.Ecto.Timestamps: (Poison.EncodeError) unable to encode value: {0, 0} #54

Closed joshrieken closed 8 years ago

joshrieken commented 8 years ago

In my web.ex, I have:

  def model do
    quote do
      use Timex.Ecto.Timestamps
      ...
    end
  end

I have a function in my view for rendering JSON:

  def render("transaction.json", %{transaction: transaction}) do
    %{
      inserted_at:           transaction.inserted_at,
      updated_at:            transaction.updated_at,
      ...
    }
  end

This view raises (Poison.EncodeError) unable to encode value: {0, 0}.

When I remove Timex.Ecto.Timestamps from web.ex, it renders as expected.

bitwalker commented 8 years ago

Ah, yes this is due to the fact that Elixir's date/time types store microseconds as a tuple of {microseconds, precision}. I would expect you would want to return timestamps in seconds since UNIX epoch when generating JSON though, no? I would use Timex.to_unix(transaction.inserted_at) instead, otherwise you'll just get an object with fields like year, month, etc.

joshrieken commented 8 years ago

Ah, yes, that is a much better way. I'm not sure why I expected it to automatically do that. Thank you!