How to use DateTime in Absinthe

Hi, what’s up everyone?

I’d be very grateful if someone wiser the me could open up this following error message a bit:

DateTime.to_iso8601/2 expects format to be :extended or :basic, got: :extended

I read it over and over again but my logic just fails me. It wants :extended but gets :extended. Pretty deep and almost poetic but not very helpful…

I’d really fancy some datetimes on my Absinthe type, like this:

import_types Absinthe.Type.Custom

  object :user do
    field :id, :id
    field :updated_at, :datetime
    field :inserted_at, :datetime
  end

I also tried to use my own scalar type instead of the import_types, like this:

  scalar :datetime do
    parse fn input ->
      case DateTime.from_iso8601(input.value) do
        {:ok, datetime} -> {:ok, datetime}
        _ -> :error
      end
    end

    serialize fn datetime ->
      DateTime.to_iso8601(datetime)
    end
  end

…but this resulted the very same error message.

So what am I doing wrong or is there a better way to do this?

Interesting! If you do:

    serialize fn datetime ->
      IO.inspect datetime
      DateTime.to_iso8601(datetime)
    end

What value do you get printed?

I get ~N[2017-10-07 08:08:44.051815] which seems right

Ah no that isn’t, that’s a NaiveDateTime not a DateTime. It lacks timezone information.

Right, actually I just figured it out as you were writing.

  DateTime.from_naive!(datetime, "Etc/UTC")
  |> DateTime.to_iso8601()

seems to do the trick!

Thank you!

1 Like

Can’t you just do NaiveDateTime.to_iso8601(datetime)? (it has an optional second argument if you need it too).

1 Like

For sure. I ended up adding the timezones to my dates.

Problem solved, but I still wonder about that error message…

Yeah that’s from the DateTime module itself, could probably be better:

iex(2)> NaiveDateTime.utc_now |> DateTime.to_iso8601
** (ArgumentError) DateTime.to_iso8601/2 expects format to be :extended or :basic, got: :extended
    (elixir) lib/calendar/datetime.ex:345: DateTime.to_iso8601/2

2 Likes